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-gui/src/main/java/jadx/gui/jobs/TaskStatus.java
jadx-gui/src/main/java/jadx/gui/jobs/TaskStatus.java
package jadx.gui.jobs; public enum TaskStatus { WAIT, STARTED, COMPLETE, CANCEL_BY_USER, CANCEL_BY_TIMEOUT, CANCEL_BY_MEMORY, ERROR }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/jobs/ITaskProgress.java
jadx-gui/src/main/java/jadx/gui/jobs/ITaskProgress.java
package jadx.gui.jobs; public interface ITaskProgress { int progress(); int total(); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/jobs/SilentTask.java
jadx-gui/src/main/java/jadx/gui/jobs/SilentTask.java
package jadx.gui.jobs; import jadx.api.utils.tasks.ITaskExecutor; import jadx.core.utils.tasks.TaskExecutor; /** * Simple and short task, will not show progress */ public class SilentTask extends CancelableBackgroundTask { private final Runnable task; public SilentTask(Runnable task) { this.task = task; } @Override public boolean isSilent() { return true; } @Override public String getTitle() { return "<silent>"; } @Override public ITaskExecutor scheduleTasks() { TaskExecutor executor = new TaskExecutor(); executor.addSequentialTask(task); return executor; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/jobs/TaskProgress.java
jadx-gui/src/main/java/jadx/gui/jobs/TaskProgress.java
package jadx.gui.jobs; import jadx.gui.utils.UiUtils; public class TaskProgress implements ITaskProgress { private int progress; private int total; public TaskProgress() { this(0, 100); } public TaskProgress(long progress, long total) { this(UiUtils.calcProgress(progress, total), 100); } public TaskProgress(int progress, int total) { this.progress = progress; this.total = total; } @Override public int progress() { return progress; } @Override public int total() { return total; } public void updateProgress(int progress) { this.progress = progress; } public void updateTotal(int total) { this.total = total; } @Override public String toString() { return "TaskProgress{" + progress + " of " + total + '}'; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/jobs/IBackgroundTask.java
jadx-gui/src/main/java/jadx/gui/jobs/IBackgroundTask.java
package jadx.gui.jobs; import java.util.function.Consumer; import org.jetbrains.annotations.Nullable; import jadx.api.utils.tasks.ITaskExecutor; public interface IBackgroundTask extends Cancelable { String getTitle(); ITaskExecutor scheduleTasks(); /** * Called on executor thread after the all jobs finished. */ default void onDone(ITaskInfo taskInfo) { } /** * Executed on the Event Dispatch Thread after the all jobs finished. */ default void onFinish(ITaskInfo taskInfo) { } default boolean canBeCanceled() { return false; } /** * Global (for all jobs) time limit in milliseconds (0 - to disable). */ default int timeLimit() { return 0; } /** * Executor will check memory usage on every tick and cancel job if no free memory available. */ default boolean checkMemoryUsage() { return false; } /** * Get task progress (Optional) */ default @Nullable ITaskProgress getTaskProgress() { return null; } /** * Return progress notifications listener (use executor tick rate and thread) (Optional) */ default @Nullable Consumer<ITaskProgress> getProgressListener() { return null; } /** * Silent task: don't show progress */ default boolean isSilent() { return false; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/logs/LogAppender.java
jadx-gui/src/main/java/jadx/gui/logs/LogAppender.java
package jadx.gui.logs; import org.apache.commons.lang3.StringUtils; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.gui.utils.UiUtils; import static jadx.plugins.script.runtime.ScriptRuntime.JADX_SCRIPT_LOG_PREFIX; class LogAppender implements ILogListener { private final LogOptions options; private final RSyntaxTextArea textArea; public LogAppender(LogOptions options, RSyntaxTextArea textArea) { this.options = options; this.textArea = textArea; } @Override public void onAppend(LogEvent logEvent) { if (accept(logEvent)) { UiUtils.uiRun(() -> textArea.append(logEvent.getMsg())); } } @Override public void onReload() { UiUtils.uiRunAndWait(() -> textArea.append(StringUtils.repeat('=', 100) + '\n')); } private boolean accept(LogEvent logEvent) { boolean byLevel = logEvent.getLevel().isGreaterOrEqual(options.getLogLevel()); if (!byLevel) { return false; } switch (options.getMode()) { case ALL: return true; case ALL_SCRIPTS: return logEvent.getLoggerName().startsWith(JADX_SCRIPT_LOG_PREFIX); case CURRENT_SCRIPT: return logEvent.getLoggerName().equals(options.getFilter()); default: throw new JadxRuntimeException("Unexpected log mode: " + options.getMode()); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/logs/LogEvent.java
jadx-gui/src/main/java/jadx/gui/logs/LogEvent.java
package jadx.gui.logs; import ch.qos.logback.classic.Level; public final class LogEvent { private final Level level; private final String loggerName; private final String msg; LogEvent(Level level, String loggerName, String msg) { this.level = level; this.loggerName = loggerName; this.msg = msg; } public Level getLevel() { return level; } public String getLoggerName() { return loggerName; } public String getMsg() { return msg; } @Override public String toString() { return level + ": " + loggerName + " - " + msg; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/logs/ILogListener.java
jadx-gui/src/main/java/jadx/gui/logs/ILogListener.java
package jadx.gui.logs; public interface ILogListener { void onAppend(LogEvent logEvent); void onReload(); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/logs/LimitedQueue.java
jadx-gui/src/main/java/jadx/gui/logs/LimitedQueue.java
package jadx.gui.logs; import java.util.AbstractQueue; import java.util.ArrayDeque; import java.util.Deque; import java.util.Iterator; public class LimitedQueue<T> extends AbstractQueue<T> { private final Deque<T> deque = new ArrayDeque<>(); private final int limit; public LimitedQueue(int limit) { this.limit = limit; } @Override public Iterator<T> iterator() { return deque.iterator(); } @Override public int size() { return deque.size(); } @Override public boolean offer(T t) { deque.addLast(t); if (deque.size() > limit) { deque.removeFirst(); } return true; } @Override public T poll() { return deque.poll(); } @Override public T peek() { return deque.peek(); } @Override public void clear() { deque.clear(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/logs/LogOptions.java
jadx-gui/src/main/java/jadx/gui/logs/LogOptions.java
package jadx.gui.logs; import org.jetbrains.annotations.Nullable; import ch.qos.logback.classic.Level; import jadx.core.utils.Utils; import static jadx.plugins.script.runtime.ScriptRuntime.JADX_SCRIPT_LOG_PREFIX; public class LogOptions { /** * Store latest requested log options */ private static LogOptions current = new LogOptions(LogMode.ALL, Level.INFO, null); public static LogOptions allWithLevel(@Nullable Level logLevel) { Level level = Utils.getOrElse(logLevel, current.getLogLevel()); return store(new LogOptions(LogMode.ALL, level, null)); } public static LogOptions forLevel(@Nullable Level logLevel) { Level level = Utils.getOrElse(logLevel, current.getLogLevel()); return store(new LogOptions(current.getMode(), level, current.getFilter())); } public static LogOptions forMode(LogMode mode) { return store(new LogOptions(mode, current.getLogLevel(), current.getFilter())); } public static LogOptions forScript(String scriptName) { String filter = JADX_SCRIPT_LOG_PREFIX + scriptName; return store(new LogOptions(LogMode.CURRENT_SCRIPT, current.getLogLevel(), filter)); } public static LogOptions current() { return current; } private static LogOptions store(LogOptions logOptions) { current = logOptions; return logOptions; } private final LogMode mode; private final Level logLevel; private final @Nullable String filter; private LogOptions(LogMode mode, Level logLevel, @Nullable String filter) { this.mode = mode; this.logLevel = logLevel; this.filter = filter; } public LogMode getMode() { return mode; } public Level getLogLevel() { return logLevel; } public @Nullable String getFilter() { return filter; } @Override public String toString() { return "LogOptions{mode=" + mode + ", logLevel=" + logLevel + ", filter='" + filter + '\'' + '}'; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/logs/IssuesListener.java
jadx-gui/src/main/java/jadx/gui/logs/IssuesListener.java
package jadx.gui.logs; import javax.swing.SwingUtilities; import ch.qos.logback.classic.Level; import jadx.gui.ui.panel.IssuesPanel; import jadx.gui.utils.rx.DebounceUpdate; public class IssuesListener implements ILogListener { private final IssuesPanel issuesPanel; private final DebounceUpdate updater; private int errors = 0; private int warnings = 0; public IssuesListener(IssuesPanel issuesPanel) { this.issuesPanel = issuesPanel; this.updater = new DebounceUpdate(500, this::onUpdate); } private void onUpdate() { SwingUtilities.invokeLater(() -> issuesPanel.onUpdate(errors, warnings)); } @Override public void onAppend(LogEvent logEvent) { switch (logEvent.getLevel().toInt()) { case Level.ERROR_INT: errors++; updater.requestUpdate(); break; case Level.WARN_INT: warnings++; updater.requestUpdate(); break; } } @Override public void onReload() { errors = 0; warnings = 0; updater.requestUpdate(); } public int getErrors() { return errors; } public int getWarnings() { return warnings; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/logs/LogPanel.java
jadx-gui/src/main/java/jadx/gui/logs/LogPanel.java
package jadx.gui.logs; import java.awt.BorderLayout; import java.awt.Dimension; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.event.ChangeListener; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.jetbrains.annotations.Nullable; import ch.qos.logback.classic.Level; import jadx.gui.settings.JadxSettings; import jadx.gui.treemodel.JInputScript; import jadx.gui.treemodel.JNode; import jadx.gui.ui.MainWindow; import jadx.gui.ui.codearea.AbstractCodeArea; import jadx.gui.ui.tab.TabBlueprint; import jadx.gui.utils.NLS; public class LogPanel extends JPanel { private static final long serialVersionUID = -8077649118322056081L; private static final Level[] LEVEL_ITEMS = { Level.DEBUG, Level.INFO, Level.WARN, Level.ERROR, Level.OFF }; private final MainWindow mainWindow; private final Runnable dockAction; private final Runnable hideAction; private RSyntaxTextArea textPane; private JComboBox<LogMode> modeCb; private JComboBox<Level> levelCb; private ChangeListener activeTabListener; public LogPanel(MainWindow mainWindow, LogOptions logOptions, Runnable dockAction, Runnable hideAction) { this.mainWindow = mainWindow; this.dockAction = dockAction; this.hideAction = hideAction; initUI(logOptions); applyLogOptions(logOptions); } public void applyLogOptions(LogOptions logOptions) { if (logOptions.getMode() == LogMode.CURRENT_SCRIPT) { String scriptName = getCurrentScriptName(); if (scriptName != null) { logOptions = LogOptions.forScript(scriptName); } registerActiveTabListener(); } else { removeActiveTabListener(); } if (modeCb.getSelectedItem() != logOptions.getMode()) { modeCb.setSelectedItem(logOptions.getMode()); } if (levelCb.getSelectedItem() != logOptions.getLogLevel()) { levelCb.setSelectedItem(logOptions.getLogLevel()); } registerLogListener(logOptions); } public void loadSettings() { AbstractCodeArea.loadCommonSettings(mainWindow, textPane); } private void initUI(LogOptions logOptions) { JadxSettings settings = mainWindow.getSettings(); textPane = AbstractCodeArea.getDefaultArea(mainWindow); textPane.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15)); modeCb = new JComboBox<>(LogMode.values()); modeCb.setSelectedItem(logOptions.getMode()); modeCb.addActionListener(e -> applyLogOptions(LogOptions.forMode((LogMode) modeCb.getSelectedItem()))); JLabel modeLabel = new JLabel(NLS.str("log_viewer.mode")); modeLabel.setLabelFor(modeCb); levelCb = new JComboBox<>(LEVEL_ITEMS); levelCb.setSelectedItem(logOptions.getLogLevel()); levelCb.addActionListener(e -> applyLogOptions(LogOptions.forLevel((Level) levelCb.getSelectedItem()))); JLabel levelLabel = new JLabel(NLS.str("log_viewer.log_level")); levelLabel.setLabelFor(levelCb); JButton clearBtn = new JButton(NLS.str("log_viewer.clear")); clearBtn.addActionListener(ev -> { LogCollector.getInstance().reset(); textPane.setText(""); }); JButton dockBtn = new JButton(NLS.str(settings.isDockLogViewer() ? "log_viewer.undock" : "log_viewer.dock")); dockBtn.addActionListener(ev -> dockAction.run()); JButton hideBtn = new JButton(NLS.str("log_viewer.hide")); hideBtn.addActionListener(ev -> hideAction.run()); JPanel start = new JPanel(); start.setLayout(new BoxLayout(start, BoxLayout.LINE_AXIS)); start.add(modeLabel); start.add(Box.createRigidArea(new Dimension(5, 0))); start.add(modeCb); start.add(Box.createRigidArea(new Dimension(15, 0))); start.add(levelLabel); start.add(Box.createRigidArea(new Dimension(5, 0))); start.add(levelCb); start.add(Box.createRigidArea(new Dimension(5, 0))); JPanel end = new JPanel(); end.setLayout(new BoxLayout(end, BoxLayout.LINE_AXIS)); end.add(clearBtn); end.add(Box.createRigidArea(new Dimension(15, 0))); end.add(dockBtn); end.add(Box.createRigidArea(new Dimension(15, 0))); end.add(hideBtn); JPanel controlPane = new JPanel(); controlPane.setLayout(new BorderLayout()); controlPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); controlPane.add(start, BorderLayout.LINE_START); controlPane.add(end, BorderLayout.LINE_END); JScrollPane scrollPane = new JScrollPane(textPane); setLayout(new BorderLayout(5, 5)); add(controlPane, BorderLayout.PAGE_START); add(scrollPane, BorderLayout.CENTER); } private void registerLogListener(LogOptions logOptions) { LogCollector logCollector = LogCollector.getInstance(); logCollector.removeListenerByClass(LogAppender.class); textPane.setText(""); logCollector.registerListener(new LogAppender(logOptions, textPane)); } private @Nullable String getCurrentScriptName() { TabBlueprint selectedTab = mainWindow.getTabsController().getSelectedTab(); if (selectedTab != null) { JNode node = selectedTab.getNode(); if (node instanceof JInputScript) { return node.getName(); } } return null; } private synchronized void registerActiveTabListener() { removeActiveTabListener(); activeTabListener = e -> { String scriptName = getCurrentScriptName(); if (scriptName != null) { applyLogOptions(LogOptions.forScript(scriptName)); } }; mainWindow.getTabbedPane().addChangeListener(activeTabListener); } private synchronized void removeActiveTabListener() { if (activeTabListener != null) { mainWindow.getTabbedPane().removeChangeListener(activeTabListener); activeTabListener = null; } } public void dispose() { LogCollector.getInstance().removeListenerByClass(LogAppender.class); removeActiveTabListener(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/logs/LogMode.java
jadx-gui/src/main/java/jadx/gui/logs/LogMode.java
package jadx.gui.logs; import org.apache.commons.lang3.StringUtils; import jadx.gui.utils.NLS; public enum LogMode { ALL, ALL_SCRIPTS, CURRENT_SCRIPT; private static final String[] NLS_STRINGS = StringUtils.split(NLS.str("log_viewer.modes"), '|'); public String getLocalizedName() { return NLS_STRINGS[this.ordinal()]; } @Override public String toString() { return getLocalizedName(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/logs/LogCollector.java
jadx-gui/src/main/java/jadx/gui/logs/LogCollector.java
package jadx.gui.logs; import java.util.ArrayList; import java.util.List; import java.util.Queue; import org.jetbrains.annotations.Nullable; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import ch.qos.logback.core.Layout; public class LogCollector extends AppenderBase<ILoggingEvent> { public static final int BUFFER_SIZE = 5000; private static final LogCollector INSTANCE = new LogCollector(); public static LogCollector getInstance() { return INSTANCE; } public static void register() { Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); LoggerContext loggerContext = rootLogger.getLoggerContext(); PatternLayout layout = new PatternLayout(); layout.setContext(loggerContext); layout.setPattern("%-5level: %msg%n"); layout.start(); INSTANCE.setContext(loggerContext); INSTANCE.setLayout(layout); INSTANCE.start(); rootLogger.addAppender(INSTANCE); } private final List<ILogListener> listeners = new ArrayList<>(); private final Queue<LogEvent> buffer = new LimitedQueue<>(BUFFER_SIZE); private Layout<ILoggingEvent> layout; public LogCollector() { setName("LogCollector"); } @Override protected synchronized void append(ILoggingEvent event) { String msg = layout.doLayout(event); LogEvent logEvent = new LogEvent(event.getLevel(), event.getLoggerName(), msg); buffer.offer(logEvent); listeners.forEach(l -> l.onAppend(logEvent)); } private void setLayout(Layout<ILoggingEvent> layout) { this.layout = layout; } public synchronized void registerListener(ILogListener listener) { listeners.add(listener); buffer.forEach(listener::onAppend); } public synchronized boolean removeListener(@Nullable ILogListener listener) { if (listener == null) { return false; } return this.listeners.removeIf(l -> l == listener); } public synchronized boolean removeListenerByClass(Class<?> listenerCls) { return this.listeners.removeIf(l -> l.getClass().equals(listenerCls)); } public synchronized void reset() { buffer.clear(); listeners.forEach(ILogListener::onReload); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/ArtAdapter.java
jadx-gui/src/main/java/jadx/gui/device/debugger/ArtAdapter.java
package jadx.gui.device.debugger; public class ArtAdapter { public interface IArtAdapter { int getRuntimeRegNum(int smaliNum, int regCount, int paramStart); boolean readNullObject(); String typeForNull(); } public static IArtAdapter getAdapter(int androidReleaseVer) { if (androidReleaseVer <= 8) { return new AndroidOreoAndBelow(); } else { return new AndroidPieAndAbove(); } } public static class AndroidOreoAndBelow implements IArtAdapter { @Override public int getRuntimeRegNum(int smaliNum, int regCount, int paramStart) { int localRegCount = regCount - paramStart; return (smaliNum + localRegCount) % regCount; } @Override public boolean readNullObject() { return true; } @Override public String typeForNull() { return ""; } } public static class AndroidPieAndAbove implements IArtAdapter { @Override public int getRuntimeRegNum(int smaliNum, int regCount, int paramStart) { return smaliNum; } @Override public boolean readNullObject() { return false; } @Override public String typeForNull() { return "zero value"; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/SmaliDebuggerException.java
jadx-gui/src/main/java/jadx/gui/device/debugger/SmaliDebuggerException.java
package jadx.gui.device.debugger; public class SmaliDebuggerException extends Exception { private final int errCode; private static final long serialVersionUID = -1111111202102191403L; public SmaliDebuggerException(Exception e) { super(e); errCode = -1; } public SmaliDebuggerException(String msg) { super(msg); this.errCode = -1; } public SmaliDebuggerException(String msg, Exception e) { super(msg, e); errCode = -1; } public SmaliDebuggerException(String msg, int errCode) { super(msg); this.errCode = errCode; } public int getErrCode() { return errCode; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/RegisterObserver.java
jadx-gui/src/main/java/jadx/gui/device/debugger/RegisterObserver.java
package jadx.gui.device.debugger; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import jadx.core.dex.instructions.args.ArgType; import jadx.gui.device.debugger.SmaliDebugger.RuntimeVarInfo; import jadx.gui.device.debugger.smali.SmaliRegister; public class RegisterObserver { private Map<Long, List<Info>> infoMap; private final List<SmaliRegisterMapping> regList; private final ArtAdapter.IArtAdapter art; private final String mthFullID; private boolean hasDbgInfo = false; private RegisterObserver(ArtAdapter.IArtAdapter art, String mthFullID) { this.regList = new ArrayList<>(); this.infoMap = Collections.emptyMap(); this.art = art; this.mthFullID = mthFullID; } @NotNull public static RegisterObserver merge(List<RuntimeVarInfo> rtRegs, List<SmaliRegister> smaliRegs, ArtAdapter.IArtAdapter art, String mthFullID) { RegisterObserver adapter = new RegisterObserver(art, mthFullID); adapter.hasDbgInfo = !rtRegs.isEmpty(); if (adapter.hasDbgInfo) { adapter.infoMap = new HashMap<>(); } for (SmaliRegister sr : smaliRegs) { adapter.regList.add(new SmaliRegisterMapping(sr)); } adapter.regList.sort(Comparator.comparingInt(r -> r.getSmaliRegister().getRuntimeRegNum())); for (RuntimeVarInfo rt : rtRegs) { final SmaliRegisterMapping smaliRegMapping = adapter.getRegListEntry(rt.getRegNum()); final SmaliRegister smaliReg = smaliRegMapping.getSmaliRegister(); smaliRegMapping.addRuntimeVarInfo(rt); String type = rt.getSignature(); if (type.isEmpty()) { type = rt.getType(); } ArgType at = ArgType.parse(type); if (at != null) { type = at.toString(); } Info load = new Info(smaliReg.getRegNum(), true, rt.getName(), type); Info unload = new Info(smaliReg.getRegNum(), false, null, null); adapter.infoMap.computeIfAbsent((long) rt.getStartOffset(), k -> new ArrayList<>()) .add(load); adapter.infoMap.computeIfAbsent((long) rt.getEndOffset(), k -> new ArrayList<>()) .add(unload); } return adapter; } @NotNull public List<SmaliRegister> getInitializedList(long codeOffset) { List<SmaliRegister> ret = Collections.emptyList(); for (SmaliRegisterMapping smaliRegisterMapping : regList) { if (smaliRegisterMapping.getSmaliRegister().isInitialized(codeOffset)) { if (ret.isEmpty()) { ret = new ArrayList<>(); } ret.add(smaliRegisterMapping.getSmaliRegister()); } } return ret; } @Nullable public RuntimeVarInfo getInfo(int runtimeNum, long codeOffset) { SmaliRegisterMapping list = getRegListEntry(runtimeNum); for (RuntimeVarInfo info : list.getRuntimeVarInfoList()) { if (info.getStartOffset() > codeOffset) { break; } if (info.isInitialized(codeOffset)) { return info; } } return null; } private SmaliRegisterMapping getRegListEntry(int regNum) { try { return regList.get(regNum); } catch (IndexOutOfBoundsException e) { throw new RuntimeException( String.format("Register %d does not exist (size: %d).\n %s\n Method: %s", regNum, regList.size(), buildDeviceInfo(), mthFullID), e); } } private String buildDeviceInfo() { DebugSettings debugSettings = DebugSettings.INSTANCE; return "Device: " + debugSettings.getDevice().getDeviceInfo() + ", Android: " + debugSettings.getVer() + ", ArtAdapter: " + art.getClass().getSimpleName(); } @NotNull public List<Info> getInfoAt(long codeOffset) { if (hasDbgInfo) { List<Info> list = infoMap.get(codeOffset); if (list != null) { return list; } } return Collections.emptyList(); } public static class SmaliRegisterMapping { private final SmaliRegister smaliRegister; private List<RuntimeVarInfo> rtList = Collections.emptyList(); public SmaliRegisterMapping(SmaliRegister smaliRegister) { this.smaliRegister = smaliRegister; } public SmaliRegister getSmaliRegister() { return smaliRegister; } @NotNull public List<RuntimeVarInfo> getRuntimeVarInfoList() { return rtList; } public void addRuntimeVarInfo(RuntimeVarInfo rt) { if (rtList.isEmpty()) { rtList = new ArrayList<>(); } rtList.add(rt); } } public static class Info { private final int smaliRegNum; private final boolean load; private final String name; private final String type; private Info(int smaliRegNum, boolean load, String name, String type) { this.smaliRegNum = smaliRegNum; this.load = load; this.name = name; this.type = type; } public int getSmaliRegNum() { return smaliRegNum; } public boolean isLoad() { return load; } public String getName() { return name; } public String getType() { return type; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/SuspendInfo.java
jadx-gui/src/main/java/jadx/gui/device/debugger/SuspendInfo.java
package jadx.gui.device.debugger; public class SuspendInfo { private boolean terminated; private boolean newRound; private final InfoSetter updater = new InfoSetter(); public long getThreadID() { return updater.thread; } public long getClassID() { return updater.clazz; } public long getMethodID() { return updater.method; } public long getOffset() { return updater.offset; } InfoSetter update() { updater.changed = false; updater.nextRound(newRound); this.newRound = false; return updater; } // called by decodingLoop, to tell the updater even though the values are the same, // they are decoded from another packet, they should be treated as new. void nextRound() { newRound = true; } // according to JDWP document it's legal to fire two or more events on a same location, // e.g. one for single step and the other for breakpoint, so when this happened we only // want one of them. boolean isAnythingChanged() { return updater.changed; } public boolean isTerminated() { return terminated; } void setTerminated() { terminated = true; } static class InfoSetter { private long thread; private long clazz; private long method; private long offset; // code offset; private boolean changed; void nextRound(boolean newRound) { if (!changed) { changed = newRound; } } InfoSetter updateThread(long thread) { if (!changed) { changed = this.thread != thread; } this.thread = thread; return this; } InfoSetter updateClass(long clazz) { if (!changed) { changed = this.clazz != clazz; } this.clazz = clazz; return this; } InfoSetter updateMethod(long method) { if (!changed) { changed = this.method != method; } this.method = method; return this; } InfoSetter updateOffset(long offset) { if (!changed) { changed = this.offset != offset; } this.offset = offset; return this; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/RuntimeType.java
jadx-gui/src/main/java/jadx/gui/device/debugger/RuntimeType.java
package jadx.gui.device.debugger; import io.github.skylot.jdwp.JDWP; public enum RuntimeType { ARRAY(91, "[]"), BYTE(66, "byte"), CHAR(67, "char"), OBJECT(76, "object"), FLOAT(70, "float"), DOUBLE(68, "double"), INT(73, "int"), LONG(74, "long"), SHORT(83, "short"), VOID(86, "void"), BOOLEAN(90, "boolean"), STRING(115, "string"), THREAD(116, "thread"), THREAD_GROUP(103, "thread_group"), CLASS_LOADER(108, "class_loader"), CLASS_OBJECT(99, "class_object"); private final int jdwpTag; private final String desc; RuntimeType(int tag, String desc) { this.jdwpTag = tag; this.desc = desc; } public int getTag() { return jdwpTag; } public String getDesc() { return this.desc; } /** * Converts a <code>JDWP.Tag</code> to a {@link RuntimeType} * * @param tag * @return * @throws SmaliDebuggerException */ public static RuntimeType fromJdwpTag(int tag) throws SmaliDebuggerException { switch (tag) { case JDWP.Tag.ARRAY: return RuntimeType.ARRAY; case JDWP.Tag.BYTE: return RuntimeType.BYTE; case JDWP.Tag.CHAR: return RuntimeType.CHAR; case JDWP.Tag.OBJECT: return RuntimeType.OBJECT; case JDWP.Tag.FLOAT: return RuntimeType.FLOAT; case JDWP.Tag.DOUBLE: return RuntimeType.DOUBLE; case JDWP.Tag.INT: return RuntimeType.INT; case JDWP.Tag.LONG: return RuntimeType.LONG; case JDWP.Tag.SHORT: return RuntimeType.SHORT; case JDWP.Tag.VOID: return RuntimeType.VOID; case JDWP.Tag.BOOLEAN: return RuntimeType.BOOLEAN; case JDWP.Tag.STRING: return RuntimeType.STRING; case JDWP.Tag.THREAD: return RuntimeType.THREAD; case JDWP.Tag.THREAD_GROUP: return RuntimeType.THREAD_GROUP; case JDWP.Tag.CLASS_LOADER: return RuntimeType.CLASS_LOADER; case JDWP.Tag.CLASS_OBJECT: return RuntimeType.CLASS_OBJECT; default: throw new SmaliDebuggerException("Unexpected value: " + tag); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/DbgUtils.java
jadx-gui/src/main/java/jadx/gui/device/debugger/DbgUtils.java
package jadx.gui.device.debugger; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JadxDecompiler; import jadx.api.JavaClass; import jadx.core.deobf.NameMapper; import jadx.core.dex.info.ClassInfo; import jadx.core.dex.nodes.ClassNode; import jadx.core.utils.android.AndroidManifestParser; import jadx.core.utils.android.AppAttribute; import jadx.core.utils.android.ApplicationParams; import jadx.gui.device.debugger.smali.Smali; import jadx.gui.treemodel.JClass; import jadx.gui.ui.MainWindow; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public class DbgUtils { private static final Logger LOG = LoggerFactory.getLogger(DbgUtils.class); private static Map<ClassInfo, Smali> smaliCache = Collections.emptyMap(); protected static Smali getSmali(ClassNode topCls) { if (smaliCache == Collections.EMPTY_MAP) { smaliCache = new HashMap<>(); } return smaliCache.computeIfAbsent(topCls.getTopParentClass().getClassInfo(), c -> Smali.disassemble(topCls)); } public static String getSmaliCode(ClassNode topCls) { Smali smali = getSmali(topCls); if (smali != null) { return smali.getCode(); } return null; } public static Entry<String, Integer> getCodeOffsetInfoByLine(JClass cls, int line) { Smali smali = getSmali(cls.getCls().getClassNode().getTopParentClass()); if (smali != null) { return smali.getMthFullIDAndCodeOffsetByLine(line); } return null; } public static String[] sepClassAndMthSig(String fullSig) { int pos = fullSig.indexOf('('); if (pos != -1) { pos = fullSig.lastIndexOf('.', pos); if (pos != -1) { String[] sigs = new String[2]; sigs[0] = fullSig.substring(0, pos); sigs[1] = fullSig.substring(pos + 1); return sigs; } } return null; } // doesn't replace $ public static String classSigToRawFullName(String clsSig) { if (clsSig != null && clsSig.startsWith("L") && clsSig.endsWith(";")) { clsSig = clsSig.substring(1, clsSig.length() - 1) .replace("/", "."); } return clsSig; } // replaces $ public static String classSigToFullName(String clsSig) { if (clsSig != null && clsSig.startsWith("L") && clsSig.endsWith(";")) { clsSig = clsSig.substring(1, clsSig.length() - 1) .replace("/", ".") .replace("$", "."); } return clsSig; } public static String getRawFullName(JClass topCls) { return topCls.getCls().getClassNode().getClassInfo().makeRawFullName(); } public static boolean isStringObjectSig(String objectSig) { return objectSig.equals("Ljava/lang/String;"); } public static JClass getTopClassBySig(String clsSig, MainWindow mainWindow) { clsSig = DbgUtils.classSigToFullName(clsSig); JavaClass cls = mainWindow.getWrapper().getDecompiler().searchJavaClassOrItsParentByOrigFullName(clsSig); if (cls != null) { JClass jc = mainWindow.getCacheObject().getNodeCache().makeFrom(cls); return jc.getRootClass(); } return null; } public static JClass getJClass(JavaClass cls, MainWindow mainWindow) { return mainWindow.getCacheObject().getNodeCache().makeFrom(cls); } public static ClassNode getClassNodeBySig(String clsSig, MainWindow mainWindow) { clsSig = DbgUtils.classSigToFullName(clsSig); return mainWindow.getWrapper().getDecompiler().searchClassNodeByOrigFullName(clsSig); } public static boolean isPrintableChar(int c) { return 32 <= c && c <= 126; } public static final class AppData { private final String appPackage; private final JavaClass mainActivityCls; public AppData(String appPackage, JavaClass mainActivityCls) { this.appPackage = appPackage; this.mainActivityCls = mainActivityCls; } public String getAppPackage() { return appPackage; } public JavaClass getMainActivityCls() { return mainActivityCls; } public String getProcessName() { return appPackage + '/' + mainActivityCls.getClassNode().getClassInfo().getFullName(); } } public static @Nullable AppData parseAppData(MainWindow mw) { JadxDecompiler decompiler = mw.getWrapper().getDecompiler(); String appPkg = decompiler.getRoot().getAppPackage(); if (appPkg == null) { UiUtils.errorMessage(mw, NLS.str("error_dialog.not_found", "App package")); return null; } AndroidManifestParser parser = new AndroidManifestParser( AndroidManifestParser.getAndroidManifest(decompiler.getResources()), EnumSet.of(AppAttribute.MAIN_ACTIVITY), decompiler.getArgs().getSecurity()); if (!parser.isManifestFound()) { UiUtils.errorMessage(mw, NLS.str("error_dialog.not_found", "AndroidManifest.xml")); return null; } ApplicationParams results = parser.parse(); String mainActivityName = results.getMainActivity(); if (mainActivityName == null) { UiUtils.errorMessage(mw, NLS.str("adb_dialog.msg_read_mani_fail")); return null; } if (!NameMapper.isValidFullIdentifier(mainActivityName)) { UiUtils.errorMessage(mw, "Invalid main activity name"); return null; } JavaClass mainActivityClass = results.getMainActivityJavaClass(decompiler); if (mainActivityClass == null) { UiUtils.errorMessage(mw, NLS.str("error_dialog.not_found", "Main activity class")); return null; } return new AppData(appPkg, mainActivityClass); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/EventListenerAdapter.java
jadx-gui/src/main/java/jadx/gui/device/debugger/EventListenerAdapter.java
package jadx.gui.device.debugger; import io.github.skylot.jdwp.JDWP.Event.Composite.BreakpointEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.ClassPrepareEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.ClassUnloadEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.ExceptionEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.FieldAccessEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.FieldModificationEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MethodEntryEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MethodExitEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MethodExitWithReturnValueEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MonitorContendedEnterEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MonitorContendedEnteredEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MonitorWaitEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MonitorWaitedEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.SingleStepEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.ThreadDeathEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.ThreadStartEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.VMDeathEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.VMStartEvent; abstract class EventListenerAdapter { void onVMStart(VMStartEvent event) { } void onVMDeath(VMDeathEvent event) { } void onSingleStep(SingleStepEvent event) { } void onBreakpoint(BreakpointEvent event) { } void onMethodEntry(MethodEntryEvent event) { } void onMethodExit(MethodExitEvent event) { } void onMethodExitWithReturnValue(MethodExitWithReturnValueEvent event) { } void onMonitorContendedEnter(MonitorContendedEnterEvent event) { } void onMonitorContendedEntered(MonitorContendedEnteredEvent event) { } void onMonitorWait(MonitorWaitEvent event) { } void onMonitorWaited(MonitorWaitedEvent event) { } void onException(ExceptionEvent event) { } void onThreadStart(ThreadStartEvent event) { } void onThreadDeath(ThreadDeathEvent event) { } void onClassPrepare(ClassPrepareEvent event) { } void onClassUnload(ClassUnloadEvent event) { } void onFieldAccess(FieldAccessEvent event) { } void onFieldModification(FieldModificationEvent event) { } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/DebugController.java
jadx-gui/src/main/java/jadx/gui/device/debugger/DebugController.java
package jadx.gui.device.debugger; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.swing.JOptionPane; import javax.swing.tree.DefaultMutableTreeNode; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.dex.info.FieldInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.utils.StringUtils; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.gui.device.debugger.BreakpointManager.FileBreakpoint; import jadx.gui.device.debugger.SmaliDebugger.Frame; import jadx.gui.device.debugger.SmaliDebugger.RuntimeBreakpoint; import jadx.gui.device.debugger.SmaliDebugger.RuntimeDebugInfo; import jadx.gui.device.debugger.SmaliDebugger.RuntimeField; import jadx.gui.device.debugger.SmaliDebugger.RuntimeRegister; import jadx.gui.device.debugger.SmaliDebugger.RuntimeValue; import jadx.gui.device.debugger.SmaliDebugger.RuntimeVarInfo; import jadx.gui.device.debugger.smali.Smali; import jadx.gui.device.debugger.smali.SmaliRegister; import jadx.gui.treemodel.JClass; import jadx.gui.ui.panel.IDebugController; import jadx.gui.ui.panel.JDebuggerPanel; import jadx.gui.ui.panel.JDebuggerPanel.IListElement; import jadx.gui.ui.panel.JDebuggerPanel.ValueTreeNode; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public final class DebugController implements SmaliDebugger.SuspendListener, IDebugController { private static final Logger LOG = LoggerFactory.getLogger(DebugController.class); private static final String ONCREATE_SIGNATURE = "onCreate(Landroid/os/Bundle;)V"; private static final Map<String, RuntimeType> TYPE_MAP = new HashMap<>(); private static final RuntimeType[] POSSIBLE_TYPES = { RuntimeType.OBJECT, RuntimeType.INT, RuntimeType.LONG }; private static final int DEFAULT_CACHE_SIZE = 512; private JDebuggerPanel debuggerPanel; private SmaliDebugger debugger; private ArtAdapter.IArtAdapter art; private final CurrentInfo cur = new CurrentInfo(); private BreakpointStore bpStore; private boolean updateAllFldAndReg = false; // update all fields and registers private ValueTreeNode toBeUpdatedTreeNode; // a field or register number. private volatile boolean isSuspended = true; private boolean hasResumed; private ResumeCmd run; private ResumeCmd stepOver; private ResumeCmd stepInto; private ResumeCmd stepOut; private StateListener stateListener; private final Map<String, RegisterObserver> regAdaMap = new ConcurrentHashMap<>(); private final ExecutorService updateQueue = Executors.newSingleThreadExecutor(); private final ExecutorService lazyQueue = Executors.newSingleThreadExecutor(); @Override public boolean startDebugger(JDebuggerPanel debuggerPanel, String adbHost, int adbPort, int androidVer) { if (TYPE_MAP.isEmpty()) { initTypeMap(); } this.debuggerPanel = debuggerPanel; UiUtils.uiRunAndWait(debuggerPanel::resetUI); try { debugger = SmaliDebugger.attach(adbHost, adbPort, this); } catch (SmaliDebuggerException e) { JOptionPane.showMessageDialog(debuggerPanel.getMainWindow(), e.getMessage(), NLS.str("error_dialog.title"), JOptionPane.ERROR_MESSAGE); logErr(e); return false; } art = ArtAdapter.getAdapter(androidVer); resetAllInfo(); hasResumed = false; run = debugger::resume; stepOver = debugger::stepOver; stepInto = debugger::stepInto; stepOut = debugger::stepOut; stopAtOnCreate(); if (bpStore == null) { bpStore = new BreakpointStore(); } else { bpStore.reset(); } BreakpointManager.setDebugController(this); initBreakpoints(BreakpointManager.getAllBreakpoints()); return true; } private void openMainActivityTab(JClass mainActivity) { String fullID = DbgUtils.getRawFullName(mainActivity) + "." + ONCREATE_SIGNATURE; Smali smali = DbgUtils.getSmali(mainActivity.getCls().getClassNode()); int pos = smali.getMethodDefPos(fullID); int finalPos = Math.max(1, pos); debuggerPanel.scrollToSmaliLine(mainActivity, finalPos, true); } private void stopAtOnCreate() { DbgUtils.AppData appData = DbgUtils.parseAppData(debuggerPanel.getMainWindow()); if (appData == null) { debuggerPanel.log("Failed to set breakpoint at onCreate, you have to do it yourself."); return; } JClass mainActivity = DbgUtils.getJClass(appData.getMainActivityCls(), debuggerPanel.getMainWindow()); lazyQueue.execute(() -> openMainActivityTab(mainActivity)); String clsSig = DbgUtils.getRawFullName(mainActivity); try { long id = debugger.getClassID(clsSig, true); if (id != -1) { return; // this app is running, we can't stop at onCreate anymore. } debuggerPanel.log(String.format("Breakpoint will set at %s.%s", clsSig, ONCREATE_SIGNATURE)); debugger.regMethodEntryEventSync(clsSig, ONCREATE_SIGNATURE::equals); } catch (SmaliDebuggerException e) { logErr(e, String.format("Failed set breakpoint at %s.%s", clsSig, ONCREATE_SIGNATURE)); } } @Override public boolean isSuspended() { return isSuspended; } @Override public boolean isDebugging() { return debugger != null; } @Override public boolean run() { return execResumeCmd(run); } @Override public boolean stepInto() { return execResumeCmd(stepInto); } @Override public boolean stepOver() { return execResumeCmd(stepOver); } @Override public boolean stepOut() { return execResumeCmd(stepOut); } @Override public boolean pause() { if (isDebugging()) { try { debugger.suspend(); } catch (SmaliDebuggerException e) { logErr(e); return false; } setDebuggerState(true, false); resetAllInfo(); } return true; } @Override public boolean stop() { if (isDebugging()) { try { debugger.exit(); } catch (SmaliDebuggerException e) { logErr(e); return false; } } return true; } @Override public boolean exit() { if (isDebugging()) { setDebuggerState(true, true); stop(); debugger = null; } BreakpointManager.setDebugController(null); debuggerPanel.getMainWindow().destroyDebuggerPanel(); debuggerPanel = null; return true; } /** * @param type must be one of int, long, float, double, string or object. */ @Override public boolean modifyRegValue(ValueTreeNode valNode, ArgType type, Object value) { checkType(type, value); if (isDebugging() && isSuspended()) { return modifyValueInternal(valNode, castType(type), value); } return false; } @Override public String getProcessName() { DbgUtils.AppData appData = DbgUtils.parseAppData(debuggerPanel.getMainWindow()); if (appData == null) { return ""; } return appData.getProcessName(); } private RuntimeType castType(ArgType type) { if (type == ArgType.INT) { return RuntimeType.INT; } if (type == ArgType.STRING) { return RuntimeType.STRING; } if (type == ArgType.LONG) { return RuntimeType.LONG; } if (type == ArgType.FLOAT) { return RuntimeType.FLOAT; } if (type == ArgType.DOUBLE) { return RuntimeType.DOUBLE; } if (type == ArgType.OBJECT) { return RuntimeType.OBJECT; } throw new JadxRuntimeException("Unexpected type: " + type); } protected static RuntimeType castType(String type) { RuntimeType rt = null; if (!StringUtils.isEmpty(type)) { rt = TYPE_MAP.get(type); } if (rt == null) { rt = POSSIBLE_TYPES[0]; } return rt; } private void checkType(ArgType type, Object value) { if (!(type == ArgType.INT && value instanceof Integer) && !(type == ArgType.STRING && value instanceof String) && !(type == ArgType.LONG && value instanceof Long) && !(type == ArgType.FLOAT && value instanceof Float) && !(type == ArgType.DOUBLE && value instanceof Double) && !(type == ArgType.OBJECT && value instanceof Long)) { throw new JadxRuntimeException("Type must be one of int, long, float, double, String or Object."); } } private boolean modifyValueInternal(ValueTreeNode valNode, RuntimeType type, Object value) { if (valNode instanceof RegTreeNode) { try { RegTreeNode regNode = (RegTreeNode) valNode; debugger.setValueSync( regNode.getRuntimeRegNum(), type, value, cur.frame.getThreadID(), cur.frame.getFrame().getID()); lazyQueue.execute(() -> { setRegsNotUpdated(); updateRegister((RegTreeNode) valNode, type, true); }); } catch (SmaliDebuggerException e) { logErr(e); return false; } } else if (valNode instanceof FieldTreeNode) { // TODO: check type. FieldTreeNode fldNode = (FieldTreeNode) valNode; try { debugger.setValueSync( fldNode.getObjectID(), ((RuntimeField) fldNode.getRuntimeValue()).getFieldID(), fldNode.getRuntimeField().getType(), value); lazyQueue.execute(() -> { updateField((FieldTreeNode) valNode); }); } catch (SmaliDebuggerException e) { logErr(e); return false; } } return true; } private interface ResumeCmd { void exec() throws SmaliDebuggerException; } private boolean execResumeCmd(ResumeCmd cmd) { if (!hasResumed) { if (cmd != run) { return false; } hasResumed = true; } if (isDebugging() && isSuspended()) { updateAllFldAndReg = cmd == run; setDebuggerState(false, false); try { cmd.exec(); return true; } catch (SmaliDebuggerException e) { logErr(e); setDebuggerState(true, false); } } return false; } /** * @param suspended suspended by step, breakpoint, etc.. * @param stopped remote app had been terminated, it's used to * change icons only, to check if it's running use isDebugging() instead. */ private void setDebuggerState(boolean suspended, boolean stopped) { isSuspended = suspended; if (stopped) { hasResumed = false; } if (stateListener != null) { stateListener.onStateChanged(suspended, stopped); } } @Override public void setStateListener(StateListener listener) { stateListener = listener; } @Override public void onSuspendEvent(SuspendInfo info) { if (!isDebugging()) { return; } if (info.isTerminated()) { debuggerPanel.log("Debugger exited."); setDebuggerState(true, true); debugger = null; return; } setDebuggerState(true, false); long threadID = info.getThreadID(); int refreshLevel = 2; // update all threads, stack frames, registers and fields. if (cur.frame != null) { if (threadID == cur.frame.getThreadID() && info.getClassID() == cur.frame.getClsID() && info.getMethodID() == cur.frame.getMthID()) { refreshLevel = 1; // relevant registers or fields. } else { cur.frame.getClsID(); } setRegsNotUpdated(); } if (refreshLevel == 2) { updateAllInfo(threadID, info.getOffset()); } else { if (cur.smali != null && cur.frame != null) { refreshRegInfo(info.getOffset()); refreshCurFrame(threadID, info.getOffset()); if (updateAllFldAndReg) { debuggerPanel.resetRegTreeNodes(); updateAllRegisters(cur.frame); } else if (toBeUpdatedTreeNode != null) { lazyQueue.execute(() -> updateRegOrField(toBeUpdatedTreeNode)); } markCodeOffset(info.getOffset()); } else { debuggerPanel.resetRegTreeNodes(); } if (cur.frame != null) { // update current code offset in stack frame. cur.frame.updateCodeOffset(info.getOffset()); debuggerPanel.refreshStackFrameList(Collections.emptyList()); } } } private void refreshRegInfo(long codeOffset) { List<RegisterObserver.Info> list = cur.regAdapter.getInfoAt(codeOffset); for (RegisterObserver.Info info : list) { RegTreeNode reg = cur.frame.getRegNodes().get(info.getSmaliRegNum()); if (info.isLoad()) { applyDbgInfo(reg, info.getName(), info.getType()); } else { reg.setAlias(""); reg.setAbsoluteType(false); } } if (list.size() > 0) { debuggerPanel.refreshRegisterTree(); } } private void updateRegOrField(ValueTreeNode valTreeNode) { if (valTreeNode instanceof RegTreeNode) { updateRegister((RegTreeNode) valTreeNode, null, true); return; } if (valTreeNode instanceof FieldTreeNode) { updateField((FieldTreeNode) valTreeNode); return; } } public void updateField(FieldTreeNode node) { try { setFieldsNotUpdated(); debugger.getValueSync(node.getObjectID(), node.getRuntimeField()); decodeRuntimeValue(node); debuggerPanel.updateThisTree(node); } catch (SmaliDebuggerException e) { logErr(e); } } public boolean updateRegister(RegTreeNode regNode, RuntimeType type, boolean retry) { if (type == null) { if (regNode.isAbsoluteType()) { type = castType(regNode.getType()); } else { type = POSSIBLE_TYPES[0]; } } boolean ok = false; RuntimeRegister register = null; try { register = debugger.getRegisterSync( cur.frame.getThreadID(), cur.frame.getFrame().getID(), regNode.getRuntimeRegNum(), type); } catch (SmaliDebuggerException e) { if (retry) { if (debugger.errIsTypeMismatched(e.getErrCode())) { RuntimeType[] types = getPossibleTypes(type); for (RuntimeType nextType : types) { ok = updateRegister(regNode, nextType, false); if (ok) { regNode.updateType(nextType.getDesc()); break; } } } else { logErr(e.getMessage() + " for " + regNode.getName()); regNode.updateType(null); regNode.updateValue(null); } } } if (register != null) { regNode.updateReg(register); decodeRuntimeValue(regNode); } debuggerPanel.updateRegTree(regNode); return ok; } private RuntimeType[] getPossibleTypes(RuntimeType cur) { RuntimeType[] types = new RuntimeType[2]; for (int i = 0, j = 0; i < POSSIBLE_TYPES.length; i++) { if (cur != POSSIBLE_TYPES[i]) { types[j++] = POSSIBLE_TYPES[i]; } } return types; } // when single stepping we can detect which reg need to be updated. private void markNextToBeUpdated(long codeOffset) { if (codeOffset != -1) { Object rst = cur.smali.getResultRegOrField(cur.mthFullID, codeOffset); toBeUpdatedTreeNode = null; if (cur.frame != null) { if (rst instanceof Integer) { int regNum = (int) rst; if (cur.frame.getRegNodes().size() > regNum) { toBeUpdatedTreeNode = cur.frame.getRegNodes().get(regNum); } return; } if (rst instanceof FieldInfo) { FieldInfo info = (FieldInfo) rst; toBeUpdatedTreeNode = cur.frame.getFieldNodes() .stream() .filter(f -> f.getName().equals(info.getName())) .findFirst() .orElse(null); } } } } private void updateAllThreads() { List<Long> threads; try { threads = debugger.getAllThreadsSync(); } catch (SmaliDebuggerException e) { logErr(e); return; } List<ThreadBoxElement> threadEleList = new ArrayList<>(threads.size()); for (Long thread : threads) { ThreadBoxElement ele = new ThreadBoxElement(thread); threadEleList.add(ele); } debuggerPanel.refreshThreadBox(threadEleList); lazyQueue.execute(() -> { for (ThreadBoxElement ele : threadEleList) { // get thread names try { ele.setName(debugger.getThreadNameSync(ele.getThreadID())); } catch (SmaliDebuggerException e) { logErr(e); } } debuggerPanel.refreshThreadBox(Collections.emptyList()); }); } private FrameNode updateAllStackFrames(long threadID) { List<SmaliDebugger.Frame> frames = Collections.emptyList(); try { frames = debugger.getFramesSync(threadID); } catch (SmaliDebuggerException e) { logErr(e); } if (frames.isEmpty()) { return null; } List<FrameNode> frameEleList = new ArrayList<>(frames.size()); for (SmaliDebugger.Frame frame : frames) { FrameNode ele = new FrameNode(threadID, frame); frameEleList.add(ele); } FrameNode curEle = frameEleList.get(0); fetchStackFrameNames(curEle); debuggerPanel.refreshStackFrameList(frameEleList); lazyQueue.execute(() -> { // get class & method names for frames for (int i = 1; i < frameEleList.size(); i++) { fetchStackFrameNames(frameEleList.get(i)); } debuggerPanel.refreshStackFrameList(Collections.emptyList()); }); return frameEleList.get(0); } private void fetchStackFrameNames(FrameNode ele) { try { long clsID = ele.getFrame().getClassID(); String clsSig = debugger.getClassSignatureSync(clsID); String mthSig = debugger.getMethodSignatureSync(clsID, ele.getFrame().getMethodID()); ele.setSignatures(clsSig, mthSig); } catch (SmaliDebuggerException e) { logErr(e); } } private Smali decodeSmali(FrameNode frame) { if (cur.frame.getClsSig() != null) { JClass jClass = DbgUtils.getTopClassBySig(frame.getClsSig(), debuggerPanel.getMainWindow()); if (jClass != null) { ClassNode cNode = jClass.getCls().getClassNode(); cur.clsNode = jClass; cur.mthFullID = DbgUtils.classSigToRawFullName(frame.getClsSig()) + "." + frame.getMthSig(); return DbgUtils.getSmali(cNode); } } return null; } private void refreshCurFrame(long threadID, long codeOffset) { try { Frame frame = debugger.getCurrentFrame(threadID); cur.frame.setFrame(frame); cur.frame.updateCodeOffset(codeOffset); } catch (SmaliDebuggerException e) { logErr(e); } } private void updateAllFields(FrameNode frame) { List<FieldNode> fldNodes = Collections.emptyList(); String clsSig = frame.getClsSig(); if (clsSig != null) { ClassNode clsNode = DbgUtils.getClassNodeBySig(clsSig, debuggerPanel.getMainWindow()); if (clsNode != null) { fldNodes = clsNode.getFields(); } } try { long thisID = debugger.getThisID(frame.getThreadID(), frame.getFrame().getID()); List<RuntimeField> flds = debugger.getAllFieldsSync(frame.getClsID()); List<FieldTreeNode> nodes = new ArrayList<>(flds.size()); for (RuntimeField fld : flds) { FieldTreeNode fldNode = new FieldTreeNode(fld, thisID); fldNodes.stream() .filter(f -> f.getName().equals(fldNode.getName())) .findFirst() .ifPresent(smaliFld -> fldNode.setAlias(smaliFld.getAlias())); nodes.add(fldNode); } debuggerPanel.updateThisFieldNodes(nodes); frame.setFieldNodes(nodes); if (thisID > 0 && nodes.size() > 0) { lazyQueue.execute(() -> updateAllFieldValues(thisID, frame)); } } catch (SmaliDebuggerException e) { logErr(e); } } private void updateAllFieldValues(long thisID, FrameNode frame) { List<FieldTreeNode> nodes = frame.getFieldNodes(); if (nodes.size() > 0) { List<FieldTreeNode> flds = new ArrayList<>(nodes.size()); List<RuntimeField> rts = new ArrayList<>(nodes.size()); nodes.forEach(n -> { RuntimeField f = n.getRuntimeField(); if (f.isBelongToThis()) { flds.add(n); rts.add(f); } }); try { debugger.getAllFieldValuesSync(thisID, rts); flds.forEach(n -> decodeRuntimeValue(n)); debuggerPanel.refreshThisFieldTree(); } catch (SmaliDebuggerException e) { logErr(e); } } } private void updateAllRegisters(FrameNode frame) { UiUtils.uiRun(() -> { if (!buildRegTreeNodes(frame).isEmpty()) { fetchAllRegisters(frame); } }); } private void fetchAllRegisters(FrameNode frame) { List<SmaliRegister> regs = cur.regAdapter.getInitializedList(frame.getCodeOffset()); for (SmaliRegister reg : regs) { RuntimeVarInfo info = cur.regAdapter.getInfo(reg.getRuntimeRegNum(), frame.getCodeOffset()); RegTreeNode regNode = frame.getRegNodes().get(reg.getRegNum()); if (info != null) { applyDbgInfo(regNode, info); } updateRegister(regNode, null, true); } } private void applyDbgInfo(RegTreeNode rn, RuntimeVarInfo info) { applyDbgInfo(rn, info.getName(), info.getType()); } private void applyDbgInfo(RegTreeNode rn, String alias, String type) { rn.setAlias(alias); rn.updateType(type); rn.setAbsoluteType(true); } private void setRegsNotUpdated() { if (cur.frame != null) { for (RegTreeNode regNode : cur.frame.getRegNodes()) { regNode.setUpdated(false); } } } private void setFieldsNotUpdated() { if (cur.frame != null) { for (FieldTreeNode node : cur.frame.getFieldNodes()) { node.setUpdated(false); } } } private List<RegTreeNode> buildRegTreeNodes(FrameNode frame) { List<SmaliRegister> regs = cur.smali.getRegisterList(cur.mthFullID); List<RegTreeNode> regNodes = new ArrayList<>(regs.size()); List<RegTreeNode> inRtOrder = new ArrayList<>(regs.size()); regs.forEach(r -> { RegTreeNode rn = new RegTreeNode(r); regNodes.add(rn); inRtOrder.add(rn); }); inRtOrder.sort(Comparator.comparingInt(RegTreeNode::getRuntimeRegNum)); frame.setRegNodes(regNodes); debuggerPanel.updateRegTreeNodes(inRtOrder); debuggerPanel.refreshRegisterTree(); return regNodes; } private boolean decodeRuntimeValue(RuntimeValueTreeNode valNode) { RuntimeValue rValue = valNode.getRuntimeValue(); RuntimeType type = rValue.getType(); if (!valNode.isAbsoluteType()) { valNode.updateType(null); } try { switch (type) { case OBJECT: return decodeObject(valNode); case STRING: String str = "\"" + debugger.readStringSync(rValue) + "\""; valNode.updateType("java.lang.String") .updateTypeID(debugger.readID(rValue)) .updateValue(str); break; case INT: valNode.updateValue(Integer.toString(debugger.readInt(rValue))); break; case LONG: valNode.updateValue(Long.toString(debugger.readAll(rValue))); break; case ARRAY: decodeArrayVal(valNode); break; case BOOLEAN: { int b = debugger.readByte(rValue); valNode.updateValue(b == 1 ? "true" : "false"); break; } case SHORT: valNode.updateValue(Short.toString(debugger.readShort(rValue))); break; case CHAR: case BYTE: { int b = (int) debugger.readAll(rValue); if (DbgUtils.isPrintableChar(b)) { valNode.updateValue(type == RuntimeType.CHAR ? String.valueOf((char) b) : String.valueOf((byte) b)); } else { valNode.updateValue(String.valueOf(b)); } break; } case DOUBLE: double d = debugger.readDouble(rValue); valNode.updateValue(Double.toString(d)); break; case FLOAT: float f = debugger.readFloat(rValue); valNode.updateValue(Float.toString(f)); break; case VOID: valNode.updateType("void"); break; case THREAD: valNode.updateType("thread").updateTypeID(debugger.readID(rValue)); break; case THREAD_GROUP: valNode.updateType("thread_group").updateTypeID(debugger.readID(rValue)); break; case CLASS_LOADER: valNode.updateType("class_loader").updateTypeID(debugger.readID(rValue)); break; case CLASS_OBJECT: valNode.updateType("class_object").updateTypeID(debugger.readID(rValue)); break; } } catch (SmaliDebuggerException e) { logErr(e); return false; } return true; } private boolean decodeObject(RuntimeValueTreeNode valNode) { RuntimeValue rValue = valNode.getRuntimeValue(); boolean ok = true; if (debugger.readID(rValue) == 0) { if (valNode.isAbsoluteType()) { valNode.updateValue("null"); return ok; } else if (!art.readNullObject()) { valNode.updateType(art.typeForNull()); valNode.updateValue("0"); return ok; } } String sig; try { sig = debugger.readObjectSignatureSync(rValue); valNode.updateType(String.format("%s@%d", DbgUtils.classSigToRawFullName(sig), debugger.readID(rValue))); } catch (SmaliDebuggerException e) { ok = debugger.errIsInvalidObject(e.getErrCode()) && valNode instanceof RegTreeNode; if (ok) { try { RegTreeNode reg = (RegTreeNode) valNode; RuntimeRegister rr = debugger.getRegisterSync( cur.frame.getThreadID(), cur.frame.getFrame().getID(), reg.getRuntimeRegNum(), RuntimeType.INT); reg.updateReg(rr); rValue = rr; valNode.updateType(RuntimeType.INT.getDesc()); valNode.updateValue(Long.toString((int) debugger.readAll(rValue))); } catch (SmaliDebuggerException except) { logErr(except, String.format("Update %s failed, %s", valNode.getName(), except.getMessage())); valNode.updateValue(except.getMessage()); ok = false; } } else { logErr(e); } } return ok; } private void decodeArrayVal(RuntimeValueTreeNode valNode) throws SmaliDebuggerException { String type = debugger.readObjectSignatureSync(valNode.getRuntimeValue()); ArgType argType = ArgType.parse(type); String javaType = argType.toString(); Entry<Integer, List<Long>> ret = debugger.readArray(valNode.getRuntimeValue(), 0, 0); javaType = javaType.substring(0, javaType.length() - 1) + ret.getKey() + "]"; valNode.updateType(javaType + "@" + debugger.readID(valNode.getRuntimeValue())); if (argType.getArrayElement().isPrimitive()) { for (Long aLong : ret.getValue()) { valNode.add(new DefaultMutableTreeNode(Long.toString(aLong))); } return; } String typeSig = type.substring(1); if (DbgUtils.isStringObjectSig(typeSig)) { for (Long aLong : ret.getValue()) { valNode.add(new DefaultMutableTreeNode(debugger.readStringSync(aLong))); } return; } typeSig = DbgUtils.classSigToRawFullName(typeSig); for (Long aLong : ret.getValue()) { valNode.add(new DefaultMutableTreeNode(String.format("%s@%d", typeSig, aLong))); } } private void updateAllInfo(long threadID, long codeOffset) { updateQueue.execute(() -> { resetAllInfo(); cur.frame = updateAllStackFrames(threadID); if (cur.frame != null) { lazyQueue.execute(() -> updateAllFields(cur.frame)); if (cur.frame.getClsSig() == null || cur.frame.getMthSig() == null) { fetchStackFrameNames(cur.frame); } cur.smali = decodeSmali(cur.frame); if (cur.smali != null) { cur.regAdapter = regAdaMap.computeIfAbsent(cur.mthFullID, k -> RegisterObserver.merge( getRuntimeDebugInfo(cur.frame), getSmaliRegisterList(), art, cur.mthFullID)); if (cur.smali.getRegCount(cur.mthFullID) > 0) { updateAllRegisters(cur.frame); } markCodeOffset(codeOffset); } } updateAllThreads(); }); } private List<SmaliRegister> getSmaliRegisterList() { int regCount = cur.smali.getRegCount(cur.mthFullID); int paramStart = cur.smali.getParamRegStart(cur.mthFullID); List<SmaliRegister> srs = cur.smali.getRegisterList(cur.mthFullID); for (SmaliRegister sr : srs) { sr.setRuntimeRegNum(art.getRuntimeRegNum(sr.getRegNum(), regCount, paramStart)); } return srs; } private void resetAllInfo() { isSuspended = true; toBeUpdatedTreeNode = null; debuggerPanel.resetAllDebuggingInfo(); cur.reset(); } private List<RuntimeVarInfo> getRuntimeDebugInfo(FrameNode frame) { try { RuntimeDebugInfo dbgInfo = debugger.getRuntimeDebugInfo(frame.getClsID(), frame.getMthID()); if (dbgInfo != null) { return dbgInfo.getInfoList(); } } catch (SmaliDebuggerException ignore) { // logErr(e); } return Collections.emptyList(); } private void markCodeOffset(long codeOffset) { scrollToPos(codeOffset); markNextToBeUpdated(codeOffset); } private void logErr(Exception e, String extra) { debuggerPanel.log(e.getMessage()); debuggerPanel.log(extra); LOG.error(extra, e); } private void logErr(Exception e) { debuggerPanel.log(e.getMessage()); LOG.error("Debug error", e); } private void logErr(String e) { debuggerPanel.log(e); LOG.error("Debug error: {}", e); } private void scrollToPos(long codeOffset) { int pos = -1; if (codeOffset > -1) { pos = cur.smali.getInsnPosByCodeOffset(cur.mthFullID, codeOffset); } if (pos == -1) { pos = cur.smali.getMethodDefPos(cur.mthFullID); if (pos == -1) { debuggerPanel.log("Can't scroll to " + cur.mthFullID); return; } } debuggerPanel.scrollToSmaliLine(cur.clsNode, pos, true); } private void initBreakpoints(List<FileBreakpoint> fbps) { if (fbps.size() == 0) { return; } boolean fetch = true; for (FileBreakpoint fbp : fbps) { try { long id = debugger.getClassID(fbp.cls, fetch); // only fetch classes from JVM once, // if this time this class hasn't been loaded then it won't load next time, cuz JVM is freezed. fetch = false; if (id > -1) { setBreakpoint(id, fbp); } else { setDelayBreakpoint(fbp); } } catch (SmaliDebuggerException e) { logErr(e); failBreakpoint(fbp, e.getMessage()); } } } protected boolean setBreakpoint(FileBreakpoint bp) { if (!isDebugging()) { return true; } try { long cid = debugger.getClassID(bp.cls, true); if (cid > -1) { setBreakpoint(cid, bp); } else { setDelayBreakpoint(bp); } } catch (SmaliDebuggerException e) { logErr(e); BreakpointManager.failBreakpoint(bp); return false; } return true; } private void setDelayBreakpoint(FileBreakpoint bp) { boolean hasSet = bpStore.hasSetDelaied(bp.cls); bpStore.add(bp, null); if (!hasSet) { updateQueue.execute(() -> { try { debugger.regClassPrepareEventForBreakpoint(bp.cls, id -> { List<FileBreakpoint> list = bpStore.get(bp.cls); for (FileBreakpoint fbp : list) { setBreakpoint(id, fbp); } }); } catch (SmaliDebuggerException e) { logErr(e); failBreakpoint(bp, ""); } }); } } protected void setBreakpoint(long cid, FileBreakpoint fbp) { try { long mid = debugger.getMethodID(cid, fbp.mth); if (mid > -1) { RuntimeBreakpoint rbp = debugger.makeBreakpoint(cid, mid, fbp.codeOffset); debugger.setBreakpoint(rbp); bpStore.add(fbp, rbp); return; } } catch (SmaliDebuggerException e) { logErr(e); } failBreakpoint(fbp, "Failed to get method for breakpoint, " + fbp.mth + ":" + fbp.codeOffset); } private void failBreakpoint(FileBreakpoint fbp, String msg) { if (!msg.isEmpty()) { debuggerPanel.log(msg); } bpStore.removeBreakpoint(fbp); BreakpointManager.failBreakpoint(fbp); } protected boolean removeBreakpoint(FileBreakpoint fbp) { if (!isDebugging()) { return true; } RuntimeBreakpoint rbp = bpStore.removeBreakpoint(fbp); if (rbp != null) { try { debugger.removeBreakpoint(rbp); } catch (SmaliDebuggerException e) { logErr(e); return false; } } return true; } private static RuntimeBreakpoint delayBP = null; private class BreakpointStore { Map<FileBreakpoint, RuntimeBreakpoint> bpm = Collections.emptyMap(); BreakpointStore() { if (delayBP == null) { delayBP = debugger.makeBreakpoint(-1, -1, -1); } } void reset() { bpm.clear(); } boolean hasSetDelaied(String cls) { for (Entry<FileBreakpoint, RuntimeBreakpoint> entry : bpm.entrySet()) { if (entry.getValue() == delayBP && entry.getKey().cls.equals(cls)) { return true; } } return false; } List<FileBreakpoint> get(String cls) { List<FileBreakpoint> fbps = new ArrayList<>(); bpm.forEach((k, v) -> { if (v == delayBP && k.cls.equals(cls)) { fbps.add(k); bpm.remove(k); } }); return fbps; } void add(FileBreakpoint fbp, RuntimeBreakpoint rbp) { if (bpm == Collections.EMPTY_MAP) { bpm = new ConcurrentHashMap<>(); } bpm.put(fbp, rbp == null ? delayBP : rbp); } RuntimeBreakpoint removeBreakpoint(FileBreakpoint fbp) { return bpm.remove(fbp); } } public class FrameNode implements IListElement { private SmaliDebugger.Frame frame; private final long threadID; private String clsSig; private String mthSig; private StringBuilder cache; private long codeOffset = -1; private List<RegTreeNode> regNodes; private List<FieldTreeNode> thisNodes; private long thisID; public FrameNode(long threadID, SmaliDebugger.Frame frame) { cache = new StringBuilder(DEFAULT_CACHE_SIZE); this.frame = frame; this.threadID = threadID; regNodes = Collections.emptyList(); thisNodes = Collections.emptyList(); } public SmaliDebugger.Frame getFrame() { return frame; } public void setFrame(SmaliDebugger.Frame frame) { this.frame = frame; } public long getClsID() { return frame.getClassID(); } public long getMthID() { return frame.getMethodID(); } public long getThreadID() { return threadID; } public long getThisID() { return thisID; } public void setThisID(long thisID) { this.thisID = thisID; } public void setSignatures(String clsSig, String mthSig) {
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
true
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/SmaliDebugger.java
jadx-gui/src/main/java/jadx/gui/device/debugger/SmaliDebugger.java
package jadx.gui.device.debugger; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.atomic.AtomicInteger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.github.skylot.jdwp.JDWP; import io.github.skylot.jdwp.JDWP.ArrayReference.Length.LengthReplyData; import io.github.skylot.jdwp.JDWP.ByteBuffer; import io.github.skylot.jdwp.JDWP.Event.Composite.BreakpointEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.ClassPrepareEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.ClassUnloadEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.EventData; import io.github.skylot.jdwp.JDWP.Event.Composite.ExceptionEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.FieldAccessEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.FieldModificationEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MethodEntryEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MethodExitEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MethodExitWithReturnValueEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MonitorContendedEnterEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MonitorContendedEnteredEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MonitorWaitEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MonitorWaitedEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.SingleStepEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.ThreadDeathEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.ThreadStartEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.VMDeathEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.VMStartEvent; import io.github.skylot.jdwp.JDWP.EventRequest.Set.ClassMatchRequest; import io.github.skylot.jdwp.JDWP.EventRequest.Set.CountRequest; import io.github.skylot.jdwp.JDWP.EventRequest.Set.LocationOnlyRequest; import io.github.skylot.jdwp.JDWP.EventRequest.Set.StepRequest; import io.github.skylot.jdwp.JDWP.Method.VariableTableWithGeneric.VarTableWithGenericData; import io.github.skylot.jdwp.JDWP.Method.VariableTableWithGeneric.VarWithGenericSlot; import io.github.skylot.jdwp.JDWP.ObjectReference; import io.github.skylot.jdwp.JDWP.ObjectReference.ReferenceType.ReferenceTypeReplyData; import io.github.skylot.jdwp.JDWP.ObjectReference.SetValues.FieldValueSetter; import io.github.skylot.jdwp.JDWP.Packet; import io.github.skylot.jdwp.JDWP.ReferenceType.FieldsWithGeneric.FieldsWithGenericData; import io.github.skylot.jdwp.JDWP.ReferenceType.FieldsWithGeneric.FieldsWithGenericReplyData; import io.github.skylot.jdwp.JDWP.ReferenceType.MethodsWithGeneric.MethodsWithGenericData; import io.github.skylot.jdwp.JDWP.ReferenceType.MethodsWithGeneric.MethodsWithGenericReplyData; import io.github.skylot.jdwp.JDWP.ReferenceType.Signature.SignatureReplyData; import io.github.skylot.jdwp.JDWP.StackFrame.GetValues.GetValuesReplyData; import io.github.skylot.jdwp.JDWP.StackFrame.GetValues.GetValuesSlots; import io.github.skylot.jdwp.JDWP.StackFrame.SetValues.SlotValueSetter; import io.github.skylot.jdwp.JDWP.StackFrame.ThisObject.ThisObjectReplyData; import io.github.skylot.jdwp.JDWP.StringReference.Value.ValueReplyData; import io.github.skylot.jdwp.JDWP.ThreadReference.Frames.FramesReplyData; import io.github.skylot.jdwp.JDWP.ThreadReference.Frames.FramesReplyDataFrames; import io.github.skylot.jdwp.JDWP.ThreadReference.Name.NameReplyData; import io.github.skylot.jdwp.JDWP.VirtualMachine.AllClassesWithGeneric.AllClassesWithGenericData; import io.github.skylot.jdwp.JDWP.VirtualMachine.AllClassesWithGeneric.AllClassesWithGenericReplyData; import io.github.skylot.jdwp.JDWP.VirtualMachine.AllThreads.AllThreadsReplyData; import io.github.skylot.jdwp.JDWP.VirtualMachine.AllThreads.AllThreadsReplyDataThreads; import io.github.skylot.jdwp.JDWP.VirtualMachine.CreateString.CreateStringReplyData; import jadx.api.plugins.input.data.AccessFlags; import jadx.gui.device.debugger.smali.RegisterInfo; import jadx.gui.utils.IOUtils; import jadx.gui.utils.ObjectPool; // TODO: Finish error notification, inner errors should be logged let user notice. public class SmaliDebugger { private static final Logger LOG = LoggerFactory.getLogger(SmaliDebugger.class); private final JDWP jdwp; private final int localTcpPort; private final InputStream inputStream; private final OutputStream outputStream; // All event callbacks will be called in this queue, e.g. class prepare/unload private static final Executor EVENT_LISTENER_QUEUE = Executors.newSingleThreadExecutor(); // Handle callbacks of single step, breakpoint and watchpoint private static final Executor SUSPEND_LISTENER_QUEUE = Executors.newSingleThreadExecutor(); private final Map<Integer, ICommandResult> callbackMap = new ConcurrentHashMap<>(); private final Map<Integer, EventListenerAdapter> eventListenerMap = new ConcurrentHashMap<>(); private final Map<String, AllClassesWithGenericData> classMap = new ConcurrentHashMap<>(); private final Map<Long, AllClassesWithGenericData> classIDMap = new ConcurrentHashMap<>(); private final Map<Long, List<MethodsWithGenericData>> clsMethodMap = new ConcurrentHashMap<>(); private final Map<Long, List<FieldsWithGenericData>> clsFieldMap = new ConcurrentHashMap<>(); private Map<Long, Map<Long, RuntimeDebugInfo>> varMap = Collections.emptyMap(); // cls id: <mth id: var table> private final CountRequest oneOffEventReq; private final AtomicInteger idGenerator = new AtomicInteger(1); private final SuspendInfo suspendInfo = new SuspendInfo(); private final SuspendListener suspendListener; private ObjectPool<List<GetValuesSlots>> slotsPool; private ObjectPool<List<JDWP.EventRequestEncoder>> stepReqPool; private ObjectPool<SynchronousQueue<Packet>> syncQueuePool; private ObjectPool<List<Long>> fieldIdPool; private final Map<Integer, Thread> syncQueueMap = new ConcurrentHashMap<>(); private final AtomicInteger syncQueueID = new AtomicInteger(0); private static final ICommandResult SKIP_RESULT = res -> { }; private SmaliDebugger(SuspendListener suspendListener, int localTcpPort, JDWP jdwp, InputStream inputStream, OutputStream outputStream) { this.jdwp = jdwp; this.localTcpPort = localTcpPort; this.suspendListener = suspendListener; this.inputStream = inputStream; this.outputStream = outputStream; oneOffEventReq = jdwp.eventRequest().cmdSet().newCountRequest(); oneOffEventReq.count = 1; } /** * After a successful attach the remote app will be suspended, so we have times to * set breakpoints or do any other things, after that call resume() to activate the app. */ public static SmaliDebugger attach(String host, int port, SuspendListener suspendListener) throws SmaliDebuggerException { try { byte[] bytes = JDWP.IDSizes.encode().getBytes(); JDWP.setPacketID(bytes, 1); LOG.debug("Connecting to ADB {}:{}", host, port); Socket socket = new Socket(host, port); InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); socket.setSoTimeout(5000); JDWP jdwp = initJDWP(outputStream, inputStream); socket.setSoTimeout(0); // set back to 0 so the decodingLoop won't break for timeout. SmaliDebugger debugger = new SmaliDebugger(suspendListener, port, jdwp, inputStream, outputStream); debugger.decodingLoop(); debugger.listenClassUnloadEvent(); debugger.initPools(); return debugger; } catch (IOException e) { throw new SmaliDebuggerException("Attach failed", e); } } private void onSuspended(long thread, long clazz, long mth, long offset) { suspendInfo.update() .updateThread(thread) .updateClass(clazz) .updateMethod(mth) .updateOffset(offset); if (suspendInfo.isAnythingChanged()) { SUSPEND_LISTENER_QUEUE.execute(() -> suspendListener.onSuspendEvent(suspendInfo)); } } public void stepInto() throws SmaliDebuggerException { sendStepRequest(suspendInfo.getThreadID(), JDWP.StepDepth.INTO); } public void stepOver() throws SmaliDebuggerException { sendStepRequest(suspendInfo.getThreadID(), JDWP.StepDepth.OVER); } public void stepOut() throws SmaliDebuggerException { sendStepRequest(suspendInfo.getThreadID(), JDWP.StepDepth.OUT); } public void exit() throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.virtualMachine().cmdExit().encode(-1)); tryThrowError(res); } public void detach() throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.virtualMachine().cmdDispose().encode()); tryThrowError(res); } private void initPools() { slotsPool = new ObjectPool<>(() -> { List<GetValuesSlots> slots = new ArrayList<>(1); GetValuesSlots slot = jdwp.stackFrame().cmdGetValues().newValuesSlots(); slot.slot = 0; slot.sigbyte = JDWP.Tag.OBJECT; slots.add(slot); return slots; }); stepReqPool = new ObjectPool<>(() -> { List<JDWP.EventRequestEncoder> eventEncoders = new ArrayList<>(2); eventEncoders.add(jdwp.eventRequest().cmdSet().newStepRequest()); eventEncoders.add(oneOffEventReq); return eventEncoders; }); syncQueuePool = new ObjectPool<>(SynchronousQueue::new); fieldIdPool = new ObjectPool<>(() -> { List<Long> ids = new ArrayList<>(1); ids.add((long) -1); return ids; }); } /** * @param regNum If it's an argument, just pass its index, non-static method should be index + 1. * e.g. void a(int b, int c), you want the value of b, then should pass 1 (0 + 1), * this is a virtual method, so 0 is for the this object and 1 is the real index of b. * <p> * If it's a variable then should be the reg number + number of arguments and + 1 * if it's in a non-static method. * e.g. to get the value of v3 in a virtual method with 2 arguments, should pass * 6 (3 + 2 + 1 = 6). */ public RuntimeRegister getRegisterSync(long threadID, long frameID, int regNum, RuntimeType type) throws SmaliDebuggerException { List<GetValuesSlots> slots = slotsPool.get(); GetValuesSlots slot = slots.get(0); slot.slot = regNum; slot.sigbyte = (byte) type.getTag(); Packet res = sendCommandSync(jdwp.stackFrame().cmdGetValues().encode(threadID, frameID, slots)); tryThrowError(res); slotsPool.put(slots); GetValuesReplyData val = jdwp.stackFrame().cmdGetValues().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); return buildRegister(regNum, val.values.get(0).slotValue.tag, val.values.get(0).slotValue.idOrValue); } public long getThisID(long threadID, long frameID) throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.stackFrame().cmdThisObject().encode(threadID, frameID)); tryThrowError(res); ThisObjectReplyData data = jdwp.stackFrame().cmdThisObject().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); return data.objectThis.objectID; } public List<RuntimeField> getAllFieldsSync(long clsID) throws SmaliDebuggerException { return getAllFields(clsID); } public void getFieldValueSync(long clsID, RuntimeField fld) throws SmaliDebuggerException { List<RuntimeField> list = new ArrayList<>(1); list.add(fld); getAllFieldValuesSync(clsID, list); } public void getAllFieldValuesSync(long thisID, List<RuntimeField> flds) throws SmaliDebuggerException { List<Long> ids = new ArrayList<>(flds.size()); flds.forEach(f -> ids.add(f.getFieldID())); Packet res = sendCommandSync(jdwp.objectReference().cmdGetValues().encode(thisID, ids)); tryThrowError(res); ObjectReference.GetValues.GetValuesReplyData data = jdwp.objectReference().cmdGetValues().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); List<ObjectReference.GetValues.GetValuesReplyDataValues> values = data.values; for (int i = 0; i < values.size(); i++) { ObjectReference.GetValues.GetValuesReplyDataValues value = values.get(i); flds.get(i).setValue(value.value.idOrValue) .setType(RuntimeType.fromJdwpTag(value.value.tag)); } } public Frame getCurrentFrame(long threadID) throws SmaliDebuggerException { return getCurrentFrameInternal(threadID); } public List<Frame> getFramesSync(long threadID) throws SmaliDebuggerException { return getAllFrames(threadID); } public List<Long> getAllThreadsSync() throws SmaliDebuggerException { return getAllThreads(); } @Nullable public String getThreadNameSync(long threadID) throws SmaliDebuggerException { return sendThreadNameReq(threadID); } @Nullable public String getClassSignatureSync(long classID) throws SmaliDebuggerException { return getClassSignatureInternal(classID); } @Nullable public String getMethodSignatureSync(long classID, long methodID) throws SmaliDebuggerException { return getMethodSignatureInternal(classID, methodID); } public boolean errIsTypeMismatched(int errCode) { return errCode == JDWP.Error.TYPE_MISMATCH; } public boolean errIsInvalidSlot(int errCode) { return errCode == JDWP.Error.INVALID_SLOT; } public boolean errIsInvalidObject(int errCode) { return errCode == JDWP.Error.INVALID_OBJECT; } private static class ClassListenerInfo { int prepareReqID; int unloadReqID; ClassListener listener; void reset(ClassListener l) { this.listener = l; this.prepareReqID = -1; this.unloadReqID = -1; } } private ClassListenerInfo clsListener; /** * Listens for class preparation and unload events. */ public void setClassListener(ClassListener listener) throws SmaliDebuggerException { if (clsListener != null) { if (listener != clsListener.listener) { unregisterEventSync(JDWP.EventKind.CLASS_PREPARE, clsListener.prepareReqID); unregisterEventSync(JDWP.EventKind.CLASS_UNLOAD, clsListener.unloadReqID); } } else { clsListener = new ClassListenerInfo(); } clsListener.reset(listener); regClassPrepareEvent(clsListener); regClassUnloadEvent(clsListener); } private void regClassUnloadEvent(ClassListenerInfo info) throws SmaliDebuggerException { Packet res = sendCommandSync( jdwp.eventRequest().cmdSet().newClassExcludeRequest((byte) JDWP.EventKind.CLASS_UNLOAD, (byte) JDWP.SuspendPolicy.NONE, "java.*")); tryThrowError(res); info.unloadReqID = jdwp.eventRequest().cmdSet().decodeRequestID(res.getBuf(), JDWP.PACKET_HEADER_SIZE); eventListenerMap.put(info.unloadReqID, new EventListenerAdapter() { @Override void onClassUnload(ClassUnloadEvent event) { info.listener.onUnloaded(DbgUtils.classSigToRawFullName(event.signature)); } }); } private void regClassPrepareEvent(ClassListenerInfo info) throws SmaliDebuggerException { Packet res = sendCommandSync( jdwp.eventRequest().cmdSet().newClassExcludeRequest((byte) JDWP.EventKind.CLASS_PREPARE, (byte) JDWP.SuspendPolicy.NONE, "java.*")); tryThrowError(res); info.prepareReqID = jdwp.eventRequest().cmdSet().decodeRequestID(res.getBuf(), JDWP.PACKET_HEADER_SIZE); eventListenerMap.put(info.prepareReqID, new EventListenerAdapter() { @Override void onClassPrepare(ClassPrepareEvent event) { info.listener.onPrepared(DbgUtils.classSigToRawFullName(event.signature), event.typeID); } }); } public void regClassPrepareEventForBreakpoint(String clsSig, ClassPrepareListener l) throws SmaliDebuggerException { Packet res = sendCommandSync(buildClassMatchReqForBreakpoint(clsSig, JDWP.EventKind.CLASS_PREPARE)); tryThrowError(res); int reqID = jdwp.eventRequest().cmdSet().decodeRequestID(res.getBuf(), JDWP.PACKET_HEADER_SIZE); eventListenerMap.put(reqID, new EventListenerAdapter() { @Override void onClassPrepare(ClassPrepareEvent event) { EVENT_LISTENER_QUEUE.execute(() -> { try { l.onPrepared(event.typeID); } finally { eventListenerMap.remove(reqID); try { resume(); } catch (SmaliDebuggerException e) { LOG.error("Resume failed", e); } } }); } }); } public interface MethodEntryListener { /** * return true to remove */ boolean entry(String mthSig); } public void regMethodEntryEventSync(String clsSig, MethodEntryListener l) throws SmaliDebuggerException { Packet res = sendCommandSync( jdwp.eventRequest().cmdSet().newClassMatchRequest((byte) JDWP.EventKind.METHOD_ENTRY, (byte) JDWP.SuspendPolicy.ALL, clsSig)); tryThrowError(res); int reqID = jdwp.eventRequest().cmdSet().decodeRequestID(res.getBuf(), JDWP.PACKET_HEADER_SIZE); eventListenerMap.put(reqID, new EventListenerAdapter() { @Override void onMethodEntry(MethodEntryEvent event) { EVENT_LISTENER_QUEUE.execute(() -> { boolean removeListener = false; try { String sig = getMethodSignatureInternal(event.location.classID, event.location.methodID); removeListener = l.entry(sig); if (removeListener) { sendCommand(jdwp.eventRequest().cmdClear().encode((byte) JDWP.EventKind.METHOD_ENTRY, reqID), SKIP_RESULT); onSuspended(event.thread, event.location.classID, event.location.methodID, -1); eventListenerMap.remove(reqID); } } catch (SmaliDebuggerException e) { LOG.error("Method entry failed", e); } finally { if (!removeListener) { try { resume(); } catch (SmaliDebuggerException e) { LOG.error("Resume failed", e); } } } }); } }); } private void unregisterEventSync(int eventKind, int reqID) throws SmaliDebuggerException { eventListenerMap.remove(reqID); Packet rst = sendCommandSync(jdwp.eventRequest().cmdClear().encode((byte) eventKind, reqID)); tryThrowError(rst); } public String readObjectSignatureSync(RuntimeValue val) throws SmaliDebuggerException { long objID = readID(val); // get type reference by object id. Packet res = sendCommandSync(jdwp.objectReference().cmdReferenceType().encode(objID)); tryThrowError(res); ReferenceTypeReplyData data = jdwp.objectReference().cmdReferenceType().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); // get signature by type reference id. res = sendCommandSync(jdwp.referenceType().cmdSignature().encode(data.typeID)); tryThrowError(res); SignatureReplyData sigData = jdwp.referenceType().cmdSignature().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); return sigData.signature; } public String readStringSync(RuntimeValue val) throws SmaliDebuggerException { return readStringSync(readID(val)); } public String readStringSync(long id) throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.stringReference().cmdValue().encode(id)); tryThrowError(res); ValueReplyData strData = jdwp.stringReference().cmdValue().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); return strData.stringValue; } public boolean setValueSync(int runtimeRegNum, RuntimeType type, Object val, long threadID, long frameID) throws SmaliDebuggerException { if (type == RuntimeType.STRING) { long newID = createString((String) val); if (newID == -1) { return false; } val = newID; type = RuntimeType.OBJECT; } List<SlotValueSetter> setters = buildRegValueSetter(type.getTag(), runtimeRegNum); JDWP.encodeAny(setters.get(0).slotValue.idOrValue, val); Packet res = sendCommandSync(jdwp.stackFrame().cmdSetValues().encode(threadID, frameID, setters)); tryThrowError(res); return jdwp.stackFrame().cmdSetValues().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); } public boolean setValueSync(long objID, long fldID, RuntimeType type, Object val) throws SmaliDebuggerException { if (type == RuntimeType.STRING) { long newID = createString((String) val); if (newID == -1) { return false; } val = newID; } List<FieldValueSetter> setters = buildFieldValueSetter(); FieldValueSetter setter = setters.get(0); setter.fieldID = fldID; JDWP.encodeAny(setter.value.idOrValue, val); Packet res = sendCommandSync(jdwp.objectReference().cmdSetValues().encode(objID, setters)); tryThrowError(res); return jdwp.objectReference().cmdSetValues().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); } public void getValueSync(long objID, RuntimeField fld) throws SmaliDebuggerException { List<Long> ids = fieldIdPool.get(); ids.set(0, fld.getFieldID()); Packet res = sendCommandSync(jdwp.objectReference().cmdGetValues().encode(objID, ids)); tryThrowError(res); ObjectReference.GetValues.GetValuesReplyData data = jdwp.objectReference().cmdGetValues().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); fld.setValue(data.values.get(0).value.idOrValue) .setType(RuntimeType.fromJdwpTag(data.values.get(0).value.tag)); } private long createString(String localStr) throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.virtualMachine().cmdCreateString().encode(localStr)); tryThrowError(res); CreateStringReplyData id = jdwp.virtualMachine().cmdCreateString().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); return id.stringObject; } public long readID(RuntimeValue val) { return JDWP.decodeBySize(val.getRawVal().getBytes(), 0, val.getRawVal().size()); } public String readArraySignature(RuntimeValue val) throws SmaliDebuggerException { return readObjectSignatureSync(val); } public int readArrayLength(RuntimeValue val) throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.arrayReference().cmdLength().encode(readID(val))); tryThrowError(res); LengthReplyData data = jdwp.arrayReference().cmdLength().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); return data.arrayLength; } /** * @param startIndex less than 0 means 0 * @param len less than or equals 0 means the maximum value 99 or the rest of the elements. * @return An entry, The key is the total length of this array when len is &lt;= 0, otherwise 0, * the value, if this array is an object array then it's object ids. */ public Entry<Integer, List<Long>> readArray(RuntimeValue reg, int startIndex, int len) throws SmaliDebuggerException { long id = readID(reg); Entry<Integer, List<Long>> ret; if (len <= 0) { Packet res = sendCommandSync(jdwp.arrayReference().cmdLength().encode(id)); tryThrowError(res); LengthReplyData data = jdwp.arrayReference().cmdLength().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); len = Math.min(99, data.arrayLength); ret = new SimpleEntry<>(data.arrayLength, null); } else { ret = new SimpleEntry<>(0, null); } startIndex = Math.max(0, startIndex); Packet res = sendCommandSync(jdwp.arrayReference().cmdGetValues().encode(id, startIndex, len)); tryThrowError(res); JDWP.ArrayReference.GetValues.GetValuesReplyData valData = jdwp.arrayReference().cmdGetValues().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); ret.setValue(valData.values.idOrValues); return ret; } public byte readByte(RuntimeValue val) { return JDWP.decodeByte(val.getRawVal().getBytes(), 0); } public char readChar(RuntimeValue val) { return JDWP.decodeChar(val.getRawVal().getBytes(), 0); } public short readShort(RuntimeValue val) { return JDWP.decodeShort(val.getRawVal().getBytes(), 0); } public int readInt(RuntimeValue val) { return JDWP.decodeInt(val.getRawVal().getBytes(), 0); } public float readFloat(RuntimeValue val) { return JDWP.decodeFloat(val.getRawVal().getBytes(), 0); } /** * @param val has 8 bytes mostly */ public long readAll(RuntimeValue val) { return JDWP.decodeBySize(val.getRawVal().getBytes(), 0, Math.min(val.getRawVal().size(), 8)); } public double readDouble(RuntimeValue val) { return JDWP.decodeDouble(val.getRawVal().getBytes(), 0); } @Nullable public RuntimeDebugInfo getRuntimeDebugInfo(long clsID, long mthID) throws SmaliDebuggerException { Map<Long, RuntimeDebugInfo> secMap = varMap.get(clsID); RuntimeDebugInfo info = null; if (secMap != null) { info = secMap.get(mthID); } if (info == null) { info = initDebugInfo(clsID, mthID); } return info; } private RuntimeDebugInfo initDebugInfo(long clsID, long mthID) throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.method().cmdVariableTableWithGeneric.encode(clsID, mthID)); tryThrowError(res); VarTableWithGenericData data = jdwp.method().cmdVariableTableWithGeneric.decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); if (varMap == Collections.EMPTY_MAP) { varMap = new ConcurrentHashMap<>(); } RuntimeDebugInfo info = new RuntimeDebugInfo(data); varMap.computeIfAbsent(clsID, k -> new HashMap<>()).put(mthID, info); return info; } private static JDWP initJDWP(OutputStream outputStream, InputStream inputStream) throws SmaliDebuggerException { try { handShake(outputStream, inputStream); outputStream.write(JDWP.Suspend.encode().setPacketID(1).getBytes()); // suspend all threads Packet res = readPacket(inputStream); tryThrowError(res); if (res.isReplyPacket() && res.getID() == 1) { // get id sizes for decoding & encoding of jdwp packets. outputStream.write(JDWP.IDSizes.encode().setPacketID(1).getBytes()); res = readPacket(inputStream); tryThrowError(res); if (res.isReplyPacket() && res.getID() == 1) { JDWP.IDSizes.IDSizesReplyData sizes = JDWP.IDSizes.decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); return new JDWP(sizes); } } } catch (IOException e) { throw new SmaliDebuggerException(e); } throw new SmaliDebuggerException("Failed to init JDWP."); } private static void handShake(OutputStream outputStream, InputStream inputStream) throws SmaliDebuggerException { byte[] buf; try { outputStream.write(JDWP.encodeHandShakePacket()); buf = IOUtils.readNBytes(inputStream, 14); } catch (Exception e) { throw new SmaliDebuggerException("jdwp handshake failed", e); } if (buf == null || !JDWP.decodeHandShakePacket(buf)) { throw new SmaliDebuggerException("jdwp handshake bad reply"); } } private MethodsWithGenericData getMethodBySig(long classID, String sig) { List<MethodsWithGenericData> methods = clsMethodMap.get(classID); if (methods != null) { for (MethodsWithGenericData method : methods) { if (sig.startsWith(method.name + "(") && sig.endsWith(method.signature)) { return method; } } } return null; } private int genID() { return idGenerator.getAndAdd(1); } /** * Read & decode packets from Socket connection */ private void decodingLoop() { Executors.newSingleThreadExecutor().execute(() -> { boolean errFromCallback; while (true) { errFromCallback = false; try { Packet res = readPacket(inputStream); if (res == null) { break; } suspendInfo.nextRound(); ICommandResult callback = callbackMap.remove(res.getID()); if (callback != null) { if (callback != SKIP_RESULT) { errFromCallback = true; callback.onCommandReply(res); } continue; } if (res.getCommandSetID() == 64 && res.getCommandID() == 100) { // command from JVM errFromCallback = true; decodeCompositeEvents(res); } else { printUnexpectedID(res.getID()); } } catch (SmaliDebuggerException e) { LOG.error("Error in debugger decoding loop", e); if (!errFromCallback) { // fatal error break; } } } suspendInfo.setTerminated(); clearWaitingSyncQueue(); suspendListener.onSuspendEvent(suspendInfo); }); } private void sendCommand(ByteBuffer buf, ICommandResult callback) throws SmaliDebuggerException { int id = genID(); callbackMap.put(id, callback); try { outputStream.write(buf.setPacketID(id).getBytes()); } catch (IOException e) { throw new SmaliDebuggerException(e); } } /** * Do not use this method inside a ICommandResult callback, it will cause deadlock. * It should be used in a thread. */ private Packet sendCommandSync(ByteBuffer buf) throws SmaliDebuggerException { SynchronousQueue<Packet> store = syncQueuePool.get(); sendCommand(buf, res -> { try { store.put(res); } catch (Exception e) { LOG.error("Command send failed", e); } }); Integer id = syncQueueID.getAndAdd(1); try { syncQueueMap.put(id, Thread.currentThread()); return store.take(); } catch (InterruptedException e) { throw new SmaliDebuggerException(e); } finally { syncQueueMap.remove(id); syncQueuePool.put(store); } } // called by decodingLoop() when fatal error occurred, // if don't do so the store.take() may block forever. private void clearWaitingSyncQueue() { syncQueueMap.keySet().forEach(k -> { Thread t = syncQueueMap.remove(k); if (t != null) { t.interrupt(); } }); } private void printUnexpectedID(int id) throws SmaliDebuggerException { throw new SmaliDebuggerException("Missing handler for this id: " + id); } private void decodeCompositeEvents(Packet res) throws SmaliDebuggerException { EventData data = jdwp.event().cmdComposite().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); for (JDWP.EventRequestDecoder event : data.events) { EventListenerAdapter listener = eventListenerMap.get(event.getRequestID()); if (listener == null) { LOG.error("Missing handler for id: {}", event.getRequestID()); continue; } if (event instanceof VMStartEvent) { listener.onVMStart((VMStartEvent) event); return; } if (event instanceof VMDeathEvent) { listener.onVMDeath((VMDeathEvent) event); return; } if (event instanceof SingleStepEvent) { listener.onSingleStep((SingleStepEvent) event); return; } if (event instanceof BreakpointEvent) { listener.onBreakpoint((BreakpointEvent) event); return; } if (event instanceof MethodEntryEvent) { listener.onMethodEntry((MethodEntryEvent) event); return; } if (event instanceof MethodExitEvent) { listener.onMethodExit((MethodExitEvent) event); return; } if (event instanceof MethodExitWithReturnValueEvent) { listener.onMethodExitWithReturnValue((MethodExitWithReturnValueEvent) event); return; } if (event instanceof MonitorContendedEnterEvent) { listener.onMonitorContendedEnter((MonitorContendedEnterEvent) event); return; } if (event instanceof MonitorContendedEnteredEvent) { listener.onMonitorContendedEntered((MonitorContendedEnteredEvent) event); return; } if (event instanceof MonitorWaitEvent) { listener.onMonitorWait((MonitorWaitEvent) event); return; } if (event instanceof MonitorWaitedEvent) { listener.onMonitorWaited((MonitorWaitedEvent) event); return; } if (event instanceof ExceptionEvent) { listener.onException((ExceptionEvent) event); return; } if (event instanceof ThreadStartEvent) { listener.onThreadStart((ThreadStartEvent) event); return; } if (event instanceof ThreadDeathEvent) { listener.onThreadDeath((ThreadDeathEvent) event); return; } if (event instanceof ClassPrepareEvent) { listener.onClassPrepare((ClassPrepareEvent) event); return; } if (event instanceof ClassUnloadEvent) { listener.onClassUnload((ClassUnloadEvent) event); return; } if (event instanceof FieldAccessEvent) { listener.onFieldAccess((FieldAccessEvent) event); return; } if (event instanceof FieldModificationEvent) { listener.onFieldModification((FieldModificationEvent) event); return; } throw new SmaliDebuggerException("Unexpected event: " + event); } } private final EventListenerAdapter stepListener = new EventListenerAdapter() { @Override void onSingleStep(SingleStepEvent event) { onSuspended(event.thread, event.location.classID, event.location.methodID, event.location.index); } }; private void sendStepRequest(long threadID, int depth) throws SmaliDebuggerException { List<JDWP.EventRequestEncoder> stepReq = buildStepRequest(threadID, JDWP.StepSize.MIN, depth); ByteBuffer stepEncodedBuf = jdwp.eventRequest().cmdSet().encode( (byte) JDWP.EventKind.SINGLE_STEP, (byte) JDWP.SuspendPolicy.ALL, stepReq); stepReqPool.put(stepReq); sendCommand(stepEncodedBuf, res -> { tryThrowError(res); int reqID = jdwp.eventRequest().cmdSet().decodeRequestID(res.getBuf(), JDWP.PACKET_HEADER_SIZE); eventListenerMap.put(reqID, stepListener); }); resume(); } public void resume() throws SmaliDebuggerException {
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
true
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/DebugSettings.java
jadx-gui/src/main/java/jadx/gui/device/debugger/DebugSettings.java
package jadx.gui.device.debugger; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.utils.StringUtils; import jadx.gui.device.protocol.ADB; import jadx.gui.device.protocol.ADBDevice; import jadx.gui.utils.NLS; public class DebugSettings { private static final Logger LOG = LoggerFactory.getLogger(DebugSettings.class); private static final int FORWARD_TCP_PORT = 33233; public static final DebugSettings INSTANCE = new DebugSettings(); private int ver; private String pid; private String name; private ADBDevice device; private int forwardTcpPort = FORWARD_TCP_PORT; private String expectPkg = ""; private boolean autoAttachPkg = false; private DebugSettings() { } public void set(ADBDevice device, int ver, String pid, String name) { this.ver = ver; this.pid = pid; this.name = name; this.device = device; this.autoAttachPkg = false; this.expectPkg = ""; } public DebugSettings setPid(String pid) { this.pid = pid; return this; } public DebugSettings setName(String name) { this.name = name; return this; } public String forwardJDWP() { int localPort = forwardTcpPort; String resultDesc = ""; try { do { ADBDevice.ForwardResult rst = device.forwardJDWP(localPort + "", pid); if (rst.state == 0) { forwardTcpPort = localPort; return ""; } if (rst.state == 1) { if (rst.desc.contains("Only one usage of each socket address")) { // port is taken by other process if (localPort < 65536) { localPort++; // retry continue; } } } resultDesc = rst.desc; break; } while (true); } catch (Exception e) { LOG.error("JDWP forward error", e); } if (StringUtils.isEmpty(resultDesc)) { resultDesc = NLS.str("adb_dialog.forward_fail"); } return resultDesc; } // we have to remove all ports that forwarding the jdwp:pid, otherwise our JDWP handshake may fail. public void clearForward() { String jdwpPid = " jdwp:" + pid; String tcpPort = " tcp:" + forwardTcpPort; try { List<String> list = ADB.listForward(device.getDeviceInfo().getAdbHost(), device.getDeviceInfo().getAdbPort()); for (String s : list) { if (s.startsWith(device.getSerial()) && s.endsWith(jdwpPid) && !s.contains(tcpPort)) { String[] fields = s.split("\\s+"); for (String field : fields) { if (field.startsWith("tcp:")) { try { device.removeForward(field.substring("tcp:".length())); } catch (Exception e) { LOG.error("JDWP remove forward error", e); } } } } } } catch (Exception e) { LOG.error("JDWP clear forward error", e); } } public boolean isBeingDebugged() { String jdwpPid = " jdwp:" + pid; String tcpPort = " tcp:" + forwardTcpPort; try { List<String> list = ADB.listForward(device.getDeviceInfo().getAdbHost(), device.getDeviceInfo().getAdbPort()); for (String s : list) { if (s.startsWith(device.getSerial()) && s.endsWith(jdwpPid)) { return !s.contains(tcpPort); } } } catch (Exception e) { LOG.error("ADB list forward error", e); } return false; } public int getVer() { return ver; } public String getPid() { return pid; } public String getName() { return name; } public ADBDevice getDevice() { return device; } public int getForwardTcpPort() { return forwardTcpPort; } public String getExpectPkg() { return expectPkg; } public void setExpectPkg(String expectPkg) { this.expectPkg = expectPkg; } public boolean isAutoAttachPkg() { return autoAttachPkg; } public void setAutoAttachPkg(boolean autoAttachPkg) { this.autoAttachPkg = autoAttachPkg; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/LogcatController.java
jadx-gui/src/main/java/jadx/gui/device/debugger/LogcatController.java
package jadx.gui.device.debugger; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.gui.device.protocol.ADBDevice; import jadx.gui.ui.panel.LogcatPanel; public class LogcatController { private static final Logger LOG = LoggerFactory.getLogger(LogcatController.class); private final ADBDevice adbDevice; private final LogcatPanel logcatPanel; private Timer timer; private final String timezone; private LogcatInfo recent = null; private List<LogcatInfo> events = new ArrayList<>(); private LogcatFilter filter = new LogcatFilter(null, null); private String status = "null"; public LogcatController(LogcatPanel logcatPanel, ADBDevice adbDevice) throws IOException { this.adbDevice = adbDevice; this.logcatPanel = logcatPanel; this.timezone = adbDevice.getTimezone(); this.startLogcat(); } public void startLogcat() { timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { getLog(); } }, 0, 1000); this.status = "running"; } public void stopLogcat() { timer.cancel(); this.status = "stopped"; } public String getStatus() { return this.status; } public void clearLogcat() { try { adbDevice.clearLogcat(); clearEvents(); } catch (IOException e) { LOG.error("Failed to clear Logcat", e); } } private void getLog() { if (!logcatPanel.isReady()) { return; } try { byte[] buf; if (recent == null) { buf = adbDevice.getBinaryLogcat(); } else { buf = adbDevice.getBinaryLogcat(recent.getAfterTimestamp()); } if (buf == null) { return; } ByteBuffer in = ByteBuffer.wrap(buf); in.order(ByteOrder.LITTLE_ENDIAN); while (in.remaining() > 20) { LogcatInfo eInfo = null; byte[] msgBuf; short eLen = in.getShort(); short eHdrLen = in.getShort(); if (eLen + eHdrLen > in.remaining()) { return; } switch (eHdrLen) { case 20: // header length 20 == version 1 eInfo = new LogcatInfo(eLen, eHdrLen, in.getInt(), in.getInt(), in.getInt(), in.getInt(), in.get()); msgBuf = new byte[eLen]; in.get(msgBuf, 0, eLen - 1); eInfo.setMsg(msgBuf); break; case 24: // header length 24 == version 2 / 3 eInfo = new LogcatInfo(eLen, eHdrLen, in.getInt(), in.getInt(), in.getInt(), in.getInt(), in.getInt(), in.get()); msgBuf = new byte[eLen]; in.get(msgBuf, 0, eLen - 1); eInfo.setMsg(msgBuf); break; case 28: // header length 28 == version 4 eInfo = new LogcatInfo(eLen, eHdrLen, in.getInt(), in.getInt(), in.getInt(), in.getInt(), in.getInt(), in.getInt(), in.get()); msgBuf = new byte[eLen]; in.get(msgBuf, 0, eLen - 1); eInfo.setMsg(msgBuf); break; default: break; } if (eInfo == null) { return; } if (recent == null) { recent = eInfo; } else if (recent.getInstant().isBefore(eInfo.getInstant())) { recent = eInfo; } if (filter.doFilter(eInfo)) { logcatPanel.log(eInfo); } events.add(eInfo); } } catch (Exception e) { LOG.error("Failed to get logcat message", e); } } public boolean reload() { stopLogcat(); boolean ok = logcatPanel.clearLogcatArea(); if (ok) { events.forEach((eInfo) -> { if (filter.doFilter(eInfo)) { logcatPanel.log(eInfo); } }); startLogcat(); } return true; } public void clearEvents() { this.recent = null; this.events = new ArrayList<>(); } public void exit() { stopLogcat(); filter = new LogcatFilter(null, null); recent = null; } public LogcatFilter getFilter() { return this.filter; } public class LogcatFilter { private final List<Integer> pid; private List<Byte> msgType = new ArrayList<>() { { add((byte) 1); add((byte) 2); add((byte) 3); add((byte) 4); add((byte) 5); add((byte) 6); add((byte) 7); add((byte) 8); } }; public LogcatFilter(ArrayList<Integer> pid, ArrayList<Byte> msgType) { if (pid != null) { this.pid = pid; } else { this.pid = new ArrayList<>(); } if (msgType != null) { this.msgType = msgType; } } public void addPid(int pid) { if (!this.pid.contains(pid)) { this.pid.add(pid); } } public void removePid(int pid) { int pidPos = this.pid.indexOf(pid); if (pidPos >= 0) { this.pid.remove(pidPos); } } public void togglePid(int pid, boolean state) { if (state) { addPid(pid); } else { removePid(pid); } } public void addMsgType(byte msgType) { if (!this.msgType.contains(msgType)) { this.msgType.add(msgType); } } public void removeMsgType(byte msgType) { int typePos = this.msgType.indexOf(msgType); if (typePos >= 0) { this.msgType.remove(typePos); } } public void toggleMsgType(byte msgType, boolean state) { if (state) { addMsgType(msgType); } else { removeMsgType(msgType); } } public boolean doFilter(LogcatInfo inInfo) { if (pid.contains(inInfo.getPid())) { return msgType.contains(inInfo.getMsgType()); } return false; } public List<LogcatInfo> getFilteredList(List<LogcatInfo> inInfoList) { List<LogcatInfo> outInfoList = new ArrayList<>(); inInfoList.forEach((inInfo) -> { if (doFilter(inInfo)) { outInfoList.add(inInfo); } }); return outInfoList; } } public class LogcatInfo { private String msg; private final byte msgType; private final int nsec; private final int pid; private final int sec; private final int tid; private final short hdrSize; private final short len; private final short version; private int lid; private int uid; public LogcatInfo(short len, short hdrSize, int pid, int tid, int sec, int nsec, byte msgType) { this.hdrSize = hdrSize; this.len = len; this.msgType = msgType; this.nsec = nsec; this.pid = pid; this.sec = sec; this.tid = tid; this.version = 1; } // Version 2 and 3 both have the same arguments public LogcatInfo(short len, short hdrSize, int pid, int tid, int sec, int nsec, int lid, byte msgType) { this.hdrSize = hdrSize; this.len = len; this.lid = lid; this.msgType = msgType; this.nsec = nsec; this.pid = pid; this.sec = sec; this.tid = tid; this.version = 3; } public LogcatInfo(short len, short hdrSize, int pid, int tid, int sec, int nsec, int lid, int uid, byte msgType) { this.hdrSize = hdrSize; this.len = len; this.lid = lid; this.msgType = msgType; this.nsec = nsec; this.pid = pid; this.sec = sec; this.tid = tid; this.uid = uid; this.version = 4; } public void setMsg(byte[] msg) { this.msg = new String(msg); } public short getVersion() { return this.version; } public short getLen() { return this.len; } public short getHeaderLen() { return this.hdrSize; } public int getPid() { return this.pid; } public int getTid() { return this.tid; } public int getSec() { return this.sec; } public int getNSec() { return this.nsec; } public int getLid() { return this.lid; } public int getUid() { return this.uid; } public Instant getInstant() { return Instant.ofEpochSecond(getSec(), getNSec()); } public String getTimestamp() { DateTimeFormatter dtFormat = DateTimeFormatter.ofPattern("MM-dd HH:mm:ss.SSS").withZone(ZoneId.of(timezone)); return dtFormat.format(getInstant()); } public String getAfterTimestamp() { DateTimeFormatter dtFormat = DateTimeFormatter.ofPattern("MM-dd HH:mm:ss.SSS").withZone(ZoneId.of(timezone)); return dtFormat.format(getInstant().plusMillis(1)); } public byte getMsgType() { return this.msgType; } public String getMsgTypeString() { switch (getMsgType()) { case 0: return "Unknown"; case 1: return "Default"; case 2: return "Verbose"; case 3: return "Debug"; case 4: return "Info"; case 5: return "Warn"; case 6: return "Error"; case 7: return "Fatal"; case 8: return "Silent"; default: return "Unknown"; } } public String getMsg() { return this.msg; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/BreakpointManager.java
jadx-gui/src/main/java/jadx/gui/device/debugger/BreakpointManager.java
package jadx.gui.device.debugger; import java.io.Reader; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import jadx.core.dex.nodes.ClassNode; import jadx.gui.device.debugger.smali.Smali; import jadx.gui.treemodel.JClass; import static jadx.core.utils.GsonUtils.buildGson; public class BreakpointManager { private static final Logger LOG = LoggerFactory.getLogger(BreakpointManager.class); private static final Gson GSON = buildGson(); private static final Type TYPE_TOKEN = new TypeToken<Map<String, List<FileBreakpoint>>>() { }.getType(); private static @NotNull Map<String, List<FileBreakpoint>> bpm = Collections.emptyMap(); private static @Nullable Path savePath; private static DebugController debugController; private static Map<String, Entry<ClassNode, Listener>> listeners = Collections.emptyMap(); // class full name as key public static void saveAndExit() { sync(); bpm = Collections.emptyMap(); savePath = null; listeners = Collections.emptyMap(); } public static void init(@Nullable Path baseDir) { Path saveDir = baseDir != null ? baseDir : Paths.get("."); savePath = saveDir.resolve("breakpoints.json"); // TODO: move into project file or same dir as project file if (Files.exists(savePath)) { try (Reader reader = Files.newBufferedReader(savePath, StandardCharsets.UTF_8)) { bpm = GSON.fromJson(reader, TYPE_TOKEN); } catch (Exception e) { LOG.error("Failed to read breakpoints config: {}", savePath, e); } } } /** * @param listener When breakpoint is failed to set during debugging, this listener will be called. */ public static void addListener(JClass topCls, Listener listener) { if (listeners.isEmpty()) { listeners = new HashMap<>(); } listeners.put(DbgUtils.getRawFullName(topCls), new SimpleEntry<>(topCls.getCls().getClassNode(), listener)); } public static void removeListener(JClass topCls) { listeners.remove(DbgUtils.getRawFullName(topCls)); } public static List<Integer> getPositions(JClass topCls) { List<FileBreakpoint> bps = bpm.get(DbgUtils.getRawFullName(topCls)); if (bps != null && bps.size() > 0) { Smali smali = DbgUtils.getSmali(topCls.getCls().getClassNode()); if (smali != null) { List<Integer> posList = new ArrayList<>(bps.size()); for (FileBreakpoint bp : bps) { int pos = smali.getInsnPosByCodeOffset(bp.getFullMthRawID(), bp.codeOffset); if (pos > -1) { posList.add(pos); } } return posList; } } return Collections.emptyList(); } public static boolean set(JClass topCls, int line) { Entry<String, Integer> lineInfo = DbgUtils.getCodeOffsetInfoByLine(topCls, line); if (lineInfo != null) { if (bpm.isEmpty()) { bpm = new HashMap<>(); } String name = DbgUtils.getRawFullName(topCls); List<FileBreakpoint> list = bpm.computeIfAbsent(name, k -> new ArrayList<>()); FileBreakpoint bkp = list.stream() .filter(bp -> bp.codeOffset == lineInfo.getValue() && bp.getFullMthRawID().equals(lineInfo.getKey())) .findFirst() .orElse(null); boolean ok = true; if (bkp == null) { String[] sigs = DbgUtils.sepClassAndMthSig(lineInfo.getKey()); if (sigs != null && sigs.length == 2) { FileBreakpoint bp = new FileBreakpoint(sigs[0], sigs[1], lineInfo.getValue()); list.add(bp); if (debugController != null) { ok = debugController.setBreakpoint(bp); } } } return ok; } return false; } public static boolean remove(JClass topCls, int line) { Entry<String, Integer> lineInfo = DbgUtils.getCodeOffsetInfoByLine(topCls, line); if (lineInfo != null) { List<FileBreakpoint> bps = bpm.get(DbgUtils.getRawFullName(topCls)); for (Iterator<FileBreakpoint> it = bps.iterator(); it.hasNext();) { FileBreakpoint bp = it.next(); if (bp.codeOffset == lineInfo.getValue() && bp.getFullMthRawID().equals(lineInfo.getKey())) { it.remove(); if (debugController != null) { return debugController.removeBreakpoint(bp); } break; } } } return true; } private static void sync() { if (savePath == null) { return; } if (bpm.isEmpty() && !Files.exists(savePath)) { // user didn't do anything with breakpoint so don't output breakpoint file. return; } try { Files.write(savePath, GSON.toJson(bpm).getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { LOG.error("Failed to write breakpoints config: {}", savePath, e); } } public interface Listener { void breakpointDisabled(int codeOffset); } protected static class FileBreakpoint { public String cls; public String mth; public long codeOffset; public FileBreakpoint() { // needed for JSON deserialization } private FileBreakpoint(String cls, String mth, long codeOffset) { this.cls = cls; this.mth = mth; this.codeOffset = codeOffset; } protected String getFullMthRawID() { return cls + "." + mth; } @Override public int hashCode() { return Objects.hash(codeOffset, cls, mth); } @Override public boolean equals(Object obj) { if (obj instanceof FileBreakpoint) { if (obj == this) { return true; } FileBreakpoint fbp = (FileBreakpoint) obj; return fbp.codeOffset == codeOffset && fbp.cls.equals(cls) && fbp.mth.equals(mth); } return false; } } protected static List<FileBreakpoint> getAllBreakpoints() { List<FileBreakpoint> bpList = new ArrayList<>(); for (Entry<String, List<FileBreakpoint>> entry : bpm.entrySet()) { bpList.addAll(entry.getValue()); } return bpList; } protected static void failBreakpoint(FileBreakpoint bp) { Entry<ClassNode, Listener> entry = listeners.get(bp.cls); if (entry != null) { int pos = DbgUtils.getSmali(entry.getKey()) .getInsnPosByCodeOffset(bp.getFullMthRawID(), bp.codeOffset); pos = Math.max(0, pos); entry.getValue().breakpointDisabled(pos); } } protected static void setDebugController(DebugController controller) { debugController = controller; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/smali/SmaliWriter.java
jadx-gui/src/main/java/jadx/gui/device/debugger/smali/SmaliWriter.java
package jadx.gui.device.debugger.smali; import jadx.api.ICodeInfo; import jadx.api.impl.SimpleCodeInfo; import jadx.api.impl.SimpleCodeWriter; import jadx.core.dex.nodes.ClassNode; public class SmaliWriter extends SimpleCodeWriter { private int line = 0; private final ClassNode cls; public SmaliWriter(ClassNode cls) { super(cls.root().getArgs()); this.cls = cls; } public ClassNode getClassNode() { return cls; } @Override protected void addLine() { super.addLine(); line++; } @Override public int getLine() { return line; } @Override public ICodeInfo finish() { return new SimpleCodeInfo(buf.toString()); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/smali/SmaliRegister.java
jadx-gui/src/main/java/jadx/gui/device/debugger/smali/SmaliRegister.java
package jadx.gui.device.debugger.smali; public class SmaliRegister extends RegisterInfo { private final int num; private String paramName; private final int endOffset; private int startOffset; private boolean isParam; private int runtimeNum; public SmaliRegister(int num, int insnCount) { this.num = num; this.endOffset = insnCount; this.startOffset = insnCount; } public int getRuntimeRegNum() { return runtimeNum; } public void setRuntimeRegNum(int runtimeNum) { this.runtimeNum = runtimeNum; } @Override public boolean isInitialized(long codeOffset) { return codeOffset > getStartOffset() && codeOffset < getEndOffset(); } protected void setParam(String name) { paramName = name; isParam = true; } protected void setStartOffset(int off) { if (off < startOffset) { startOffset = off; } } @Override public String getName() { return paramName != null ? paramName : "v" + num; } @Override public int getRegNum() { return num; } @Override public String getType() { return ""; } @Override public String getSignature() { return null; } @Override public int getStartOffset() { return startOffset; } @Override public int getEndOffset() { return endOffset; } @Override public boolean isMarkedAsParameter() { return isParam; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/smali/RegisterInfo.java
jadx-gui/src/main/java/jadx/gui/device/debugger/smali/RegisterInfo.java
package jadx.gui.device.debugger.smali; import jadx.api.plugins.input.data.ILocalVar; public abstract class RegisterInfo implements ILocalVar { public boolean isInitialized(long codeOffset) { return codeOffset >= getStartOffset() && codeOffset < getEndOffset(); } public boolean isUnInitialized(long codeOffset) { return codeOffset < getStartOffset() || codeOffset >= getEndOffset(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/smali/Smali.java
jadx-gui/src/main/java/jadx/gui/device/debugger/smali/Smali.java
package jadx.gui.device.debugger.smali; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeInfo; import jadx.api.JadxArgs; import jadx.api.plugins.input.data.AccessFlags; import jadx.api.plugins.input.data.AccessFlagsScope; import jadx.api.plugins.input.data.ICatch; import jadx.api.plugins.input.data.IClassData; import jadx.api.plugins.input.data.ICodeReader; import jadx.api.plugins.input.data.IDebugInfo; import jadx.api.plugins.input.data.IFieldData; import jadx.api.plugins.input.data.ILocalVar; import jadx.api.plugins.input.data.IMethodData; import jadx.api.plugins.input.data.IMethodRef; import jadx.api.plugins.input.data.ITry; import jadx.api.plugins.input.data.annotations.AnnotationVisibility; import jadx.api.plugins.input.data.annotations.EncodedValue; import jadx.api.plugins.input.data.annotations.IAnnotation; import jadx.api.plugins.input.data.attributes.JadxAttrType; import jadx.api.plugins.input.data.attributes.types.AnnotationsAttr; import jadx.api.plugins.input.insns.InsnData; import jadx.api.plugins.input.insns.InsnIndexType; import jadx.api.plugins.input.insns.Opcode; import jadx.api.plugins.input.insns.custom.ISwitchPayload; import jadx.core.dex.attributes.AttributeStorage; import jadx.core.dex.instructions.IndexInsnNode; import jadx.core.dex.instructions.InsnDecoder; import jadx.core.dex.instructions.InsnType; import jadx.core.dex.instructions.InvokeNode; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.instructions.args.RegisterArg; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.utils.StringUtils; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; import static jadx.api.plugins.input.data.AccessFlagsScope.FIELD; import static jadx.api.plugins.input.data.AccessFlagsScope.METHOD; import static jadx.api.plugins.input.insns.Opcode.CONST; import static jadx.api.plugins.input.insns.Opcode.CONST_METHOD_HANDLE; import static jadx.api.plugins.input.insns.Opcode.CONST_METHOD_TYPE; import static jadx.api.plugins.input.insns.Opcode.CONST_WIDE; import static jadx.api.plugins.input.insns.Opcode.FILLED_NEW_ARRAY; import static jadx.api.plugins.input.insns.Opcode.FILLED_NEW_ARRAY_RANGE; import static jadx.api.plugins.input.insns.Opcode.FILL_ARRAY_DATA_PAYLOAD; import static jadx.api.plugins.input.insns.Opcode.INVOKE_CUSTOM; import static jadx.api.plugins.input.insns.Opcode.INVOKE_CUSTOM_RANGE; import static jadx.api.plugins.input.insns.Opcode.INVOKE_POLYMORPHIC; import static jadx.api.plugins.input.insns.Opcode.INVOKE_POLYMORPHIC_RANGE; import static jadx.api.plugins.input.insns.Opcode.PACKED_SWITCH; import static jadx.api.plugins.input.insns.Opcode.PACKED_SWITCH_PAYLOAD; import static jadx.api.plugins.input.insns.Opcode.SPARSE_SWITCH; import static jadx.api.plugins.input.insns.Opcode.SPARSE_SWITCH_PAYLOAD; public class Smali { private static final Logger LOG = LoggerFactory.getLogger(Smali.class); private static SmaliInsnDecoder insnDecoder = null; private ICodeInfo codeInfo; private final Map<String, SmaliMethodNode> insnMap = new HashMap<>(); // fullRawId of method as key private final boolean printFileOffset = true; private final boolean printBytecode = true; private boolean isJavaBytecode; private Smali() { } public static Smali disassemble(ClassNode cls) { cls = cls.getTopParentClass(); SmaliWriter code = new SmaliWriter(cls); Smali smali = new Smali(); smali.isJavaBytecode = cls.getInputFileName().endsWith(".class"); // TODO: add flag to api smali.writeClass(code, cls); smali.codeInfo = code.finish(); return smali; } public String getCode() { return codeInfo.getCodeStr(); } public int getMethodDefPos(String mthFullRawID) { SmaliMethodNode info = insnMap.get(mthFullRawID); if (info != null) { return info.getDefPos(); } return -1; } public int getRegCount(String mthFullRawID) { SmaliMethodNode info = insnMap.get(mthFullRawID); if (info != null) { return info.getRegCount(); } return -1; } public int getParamRegStart(String mthFullRawID) { SmaliMethodNode info = insnMap.get(mthFullRawID); if (info != null) { return info.getParamRegStart(); } return -1; } public int getInsnPosByCodeOffset(String mthFullRawID, long codeOffset) { SmaliMethodNode info = insnMap.get(mthFullRawID); if (info != null) { return info.getInsnPos(codeOffset); } return -1; } @Nullable public Entry<String, Integer> getMthFullIDAndCodeOffsetByLine(int line) { for (Entry<String, SmaliMethodNode> entry : insnMap.entrySet()) { Integer codeOffset = entry.getValue().getLineMapping().get(line); if (codeOffset != null) { return new SimpleEntry<>(entry.getKey(), codeOffset); } } return null; } public List<SmaliRegister> getRegisterList(String mthFullRawID) { SmaliMethodNode node = insnMap.get(mthFullRawID); if (node != null) { return node.getRegList(); } return Collections.emptyList(); } /** * @return null for no result, FieldInfo for field, Integer for register. */ @Nullable public Object getResultRegOrField(String mthFullRawID, long codeOffset) { SmaliMethodNode info = insnMap.get(mthFullRawID); if (info != null) { InsnNode insn = info.getInsnNode(codeOffset); if (insn != null) { if (insn.getType() == InsnType.IPUT) { return ((IndexInsnNode) insn).getIndex(); } if (insn.getType() == InsnType.INVOKE) { if (insn instanceof InvokeNode) { if (insn.getArgsCount() > 0) { return ((RegisterArg) insn.getArg(0)).getRegNum(); } } } RegisterArg regArg = insn.getResult(); if (regArg != null) { return regArg.getRegNum(); } } } return null; } private void writeClass(SmaliWriter smali, ClassNode cls) { IClassData clsData = cls.getClsData(); if (clsData == null) { smali.startLine(String.format("###### Class %s is created by jadx", cls.getFullName())); return; } AttributeStorage clsAttributes = AttributeStorage.fromList(clsData.getAttributes()); smali.startLine("Class: " + clsData.getType()) .startLine("AccessFlags: " + AccessFlags.format(clsData.getAccessFlags(), AccessFlagsScope.CLASS)) .startLine("SuperType: " + clsData.getSuperType()) .startLine("Interfaces: " + clsData.getInterfacesTypes()) .startLine("SourceFile: " + clsAttributes.get(JadxAttrType.SOURCE_FILE)); AnnotationsAttr annotationsAttr = clsAttributes.get(JadxAttrType.ANNOTATION_LIST); if (annotationsAttr != null) { Collection<IAnnotation> annos = annotationsAttr.getList(); if (!annos.isEmpty()) { smali.startLine(String.format("# %d annotations", annos.size())); writeAnnotations(smali, new ArrayList<>(annos)); smali.startLine(); } } List<RawField> fields = new ArrayList<>(); int[] colWidths = new int[] { 0, 0 }; // first is access flag, second is name int[] mthIndex = new int[] { 0 }; LineInfo line = new LineInfo(); clsData.visitFieldsAndMethods( f -> { RawField fld = RawField.make(f); fields.add(fld); if (fld.accessFlag.length() > colWidths[0]) { colWidths[0] = fld.accessFlag.length(); } if (fld.name.length() > colWidths[1]) { colWidths[1] = fld.name.length(); } }, m -> { if (!fields.isEmpty()) { writeFields(smali, clsData, fields, colWidths); fields.clear(); } try { writeMethod(smali, cls.getMethods().get(mthIndex[0]++), m, line); } catch (Throwable e) { IMethodRef methodRef = m.getMethodRef(); String mthFullName = methodRef.getParentClassType() + "->" + methodRef.getName(); smali.setIndent(0); smali.startLine("Failed to write method: " + mthFullName + "\n" + Utils.getStackTrace(e)); LOG.error("Failed to write smali code for method: {}", mthFullName, e); } line.reset(); }); if (!fields.isEmpty()) { // in case there's no methods. writeFields(smali, clsData, fields, colWidths); } for (ClassNode innerClass : cls.getInnerClasses()) { writeClass(smali, innerClass); } } private void writeFields(SmaliWriter smali, IClassData classData, List<RawField> fields, int[] colWidths) { int staticIdx = 0; smali.startLine().startLine("# fields"); String whites = new String(new byte[Math.max(colWidths[0], colWidths[1])]).replace("\0", " "); for (RawField fld : fields) { smali.startLine(); int pad = colWidths[0] - fld.accessFlag.length(); if (pad > 0) { fld.accessFlag += whites.substring(0, pad); } smali.add(".field ").add(fld.accessFlag); pad = colWidths[1] - fld.name.length(); if (pad > 0) { fld.name += whites.substring(0, pad); } smali.add(fld.name).add(" "); smali.add(": ").add(fld.type); if (fld.isStatic) { EncodedValue constVal = fld.attributes.get(JadxAttrType.CONSTANT_VALUE); if (constVal != null) { smali.add(" # init val = "); writeEncodedValue(smali, constVal, false); } } AnnotationsAttr annotationsAttr = fld.attributes.get(JadxAttrType.ANNOTATION_LIST); if (annotationsAttr != null) { smali.incIndent(); writeAnnotations(smali, annotationsAttr.getList()); smali.decIndent(); } } smali.startLine(); } private void writeMethod(SmaliWriter smali, MethodNode methodNode, IMethodData mth, LineInfo line) { if (insnDecoder == null) { insnDecoder = new SmaliInsnDecoder(methodNode); } smali.startLine().startLine(".method "); writeMethodDef(smali, mth, line); ICodeReader codeReader = mth.getCodeReader(); if (codeReader != null) { int regsCount = codeReader.getRegistersCount(); line.smaliMthNode.setParamRegStart(getParamStartRegNum(mth)); line.smaliMthNode.setRegCount(regsCount); Map<Long, InsnNode> nodes = new HashMap<>(codeReader.getUnitsCount() / 2); line.smaliMthNode.setInsnNodes(nodes, codeReader.getUnitsCount()); line.smaliMthNode.initRegInfoList(regsCount, codeReader.getUnitsCount()); smali.incIndent(); smali.startLine(".registers ").add(Integer.toString(regsCount)); writeTries(codeReader, line); IDebugInfo debugInfo = codeReader.getDebugInfo(); List<ILocalVar> localVars = debugInfo != null ? debugInfo.getLocalVars() : Collections.emptyList(); formatMthParamInfo(mth, smali, line, regsCount, localVars); if (debugInfo != null) { formatDbgInfo(debugInfo, localVars, line); } smali.newLine(); smali.startLine(); // first pass to fill payload offsets for switch instructions codeReader.visitInstructions(insn -> { Opcode opcode = insn.getOpcode(); if (opcode == PACKED_SWITCH || opcode == SPARSE_SWITCH) { insn.decode(); line.addPayloadOffset(insn.getOffset(), insn.getTarget()); } }); codeReader.visitInstructions(insn -> { InsnNode node = decodeInsn(insn, line); nodes.put((long) insn.getOffset(), node); }); line.write(smali); insnMap.put(methodNode.getMethodInfo().getRawFullId(), line.smaliMthNode); smali.decIndent(); } smali.startLine(".end method"); } private void writeTries(ICodeReader codeReader, LineInfo line) { List<ITry> tries = codeReader.getTries(); for (ITry aTry : tries) { int end = aTry.getEndOffset(); String tryEndTip = String.format(FMT_TRY_END_TAG, end); String tryStartTip = String.format(FMT_TRY_TAG, aTry.getStartOffset()); String tryStartTipExtra = " # :" + tryStartTip.substring(0, tryStartTip.length() - 1); line.addTip(aTry.getStartOffset(), tryStartTip, " # :" + tryEndTip.substring(0, tryEndTip.length() - 1)); line.addTip(end, tryEndTip, tryStartTipExtra); ICatch iCatch = aTry.getCatch(); int[] addresses = iCatch.getHandlers(); int addr; for (int i = 0; i < addresses.length; i++) { addr = addresses[i]; String catchTip = String.format(FMT_CATCH_TAG, addr); line.addTip(addr, catchTip, " # " + iCatch.getTypes()[i]); line.addTip(addr, catchTip, tryStartTipExtra); line.addTip(aTry.getStartOffset(), tryStartTip, " # :" + catchTip.substring(0, catchTip.length() - 1)); } addr = iCatch.getCatchAllHandler(); if (addr > -1) { String catchAllTip = String.format(FMT_CATCH_ALL_TAG, addr); line.addTip(addr, catchAllTip, tryStartTipExtra); line.addTip(aTry.getStartOffset(), tryStartTip, " # :" + catchAllTip.substring(0, catchAllTip.length() - 1)); } } } private InsnNode decodeInsn(InsnData insn, LineInfo lineInfo) { insn.decode(); InsnNode node = insnDecoder.decode(insn); formatInsn(insn, node, lineInfo); return node; } private void formatInsn(InsnData insn, InsnNode node, LineInfo line) { StringBuilder lw = line.getLineWriter(); lw.delete(0, lw.length()); fmtCols(insn, line); if (fmtPayloadInsn(insn, line)) { return; } lw.append(formatInsnName(insn)).append(" "); fmtRegs(insn, node.getType(), line); if (!tryFormatTargetIns(insn, node.getType(), line)) { if (hasLiteral(insn)) { lw.append(", ").append(literal(insn)); } else if (node.getType() == InsnType.INVOKE) { lw.append(", ").append(method(insn)); } else if (insn.getIndexType() == InsnIndexType.FIELD_REF) { lw.append(", ").append(field(insn)); } else if (insn.getIndexType() == InsnIndexType.STRING_REF) { lw.append(", ").append(str(insn)); } else if (insn.getIndexType() == InsnIndexType.TYPE_REF) { lw.append(", ").append(type(insn)); } else if (insn.getOpcode() == CONST_METHOD_HANDLE) { lw.append(", ").append(methodHandle(insn)); } else if (insn.getOpcode() == CONST_METHOD_TYPE) { lw.append(", ").append(proto(insn, insn.getIndex())); } } line.addInsnLine(insn.getOffset(), lw.toString()); } private String formatInsnName(InsnData insn) { if (isJavaBytecode) { // add api opcode, because registers not used return String.format("%-" + INSN_COL_WIDTH + "s | %-15s", insn.getOpcodeMnemonic(), insn.getOpcode().name().toLowerCase(Locale.ROOT).replace('_', '-')); } return String.format(FMT_INSN_COL, insn.getOpcodeMnemonic()); } private boolean tryFormatTargetIns(InsnData insn, InsnType insnType, LineInfo line) { switch (insnType) { case IF: { int target = insn.getTarget(); line.addTip(target, String.format(FMT_COND_TAG, target), ""); line.getLineWriter().append(", ").append(String.format(FMT_COND, target)); return true; } case GOTO: { int target = insn.getTarget(); line.addTip(target, String.format(FMT_GOTO_TAG, target), ""); line.getLineWriter().append(String.format(FMT_GOTO, target)); return true; } case FILL_ARRAY: { int target = insn.getTarget(); line.addTip(target, String.format(FMT_DATA_TAG, target), ""); line.getLineWriter().append(", ").append(String.format(FMT_DATA, target)); return true; } case SWITCH: { int target = insn.getTarget(); if (insn.getOpcode() == Opcode.PACKED_SWITCH) { line.addTip(target, String.format(FMT_P_SWITCH_TAG, target), ""); line.getLineWriter().append(", ").append(String.format(FMT_P_SWITCH, target)); } else { line.addTip(target, String.format(FMT_S_SWITCH_TAG, target), ""); line.getLineWriter().append(", ").append(String.format(FMT_S_SWITCH, target)); } return true; } } return false; } private static boolean hasStaticFlag(int flag) { return (flag & AccessFlags.STATIC) != 0; } private void writeMethodDef(SmaliWriter smali, IMethodData mth, LineInfo lineInfo) { smali.add(AccessFlags.format(mth.getAccessFlags(), METHOD)); IMethodRef methodRef = mth.getMethodRef(); methodRef.load(); lineInfo.smaliMthNode.setDefPos(smali.getLength()); smali.add(methodRef.getName()) .add('('); methodRef.getArgTypes().forEach(smali::add); smali.add(')'); smali.add(methodRef.getReturnType()); AttributeStorage mthAttributes = AttributeStorage.fromList(mth.getAttributes()); AnnotationsAttr annotationsAttr = mthAttributes.get(JadxAttrType.ANNOTATION_LIST); if (annotationsAttr != null && !annotationsAttr.isEmpty()) { smali.incIndent(); writeAnnotations(smali, annotationsAttr.getList()); smali.decIndent(); smali.startLine(); } } private void formatMthParamInfo(IMethodData mth, SmaliWriter smali, LineInfo line, int regsCount, List<ILocalVar> localVars) { List<String> types = mth.getMethodRef().getArgTypes(); if (types.isEmpty()) { return; } int paramStart = 0; int regNum = line.smaliMthNode.getParamRegStart(); if (!hasStaticFlag(mth.getAccessFlags())) { // add 'this' register line.addRegName(regNum, "p0"); line.smaliMthNode.setParamReg(regNum, "p0"); regNum++; paramStart++; } if (localVars.isEmpty()) { return; } ILocalVar[] params = new ILocalVar[regsCount]; for (ILocalVar var : localVars) { if (var.isMarkedAsParameter()) { params[var.getRegNum()] = var; } } smali.newLine(); for (String paramType : types) { ILocalVar param = params[regNum]; if (param != null) { String name = Utils.getOrElse(param.getName(), ""); String type = Utils.getOrElse(param.getSignature(), paramType); String varName = "p" + paramStart; smali.startLine(String.format(".param %s, \"%s\" # %s", varName, name, type)); line.addRegName(regNum, varName); line.smaliMthNode.setParamReg(regNum, varName); } int regSize = isWideType(paramType) ? 2 : 1; regNum += regSize; paramStart += regSize; } } private static int getParamStartRegNum(IMethodData mth) { ICodeReader codeReader = mth.getCodeReader(); if (codeReader != null) { int startNum = codeReader.getRegistersCount(); if (startNum > 0) { for (String argType : mth.getMethodRef().getArgTypes()) { if (isWideType(argType)) { startNum -= 2; } else { startNum -= 1; } } if (!hasStaticFlag(mth.getAccessFlags())) { startNum--; } return startNum; } } return -1; } private static boolean isWideType(String type) { return type.equals("D") || type.equals("J"); } private void writeAnnotations(SmaliWriter smali, List<IAnnotation> annoList) { if (annoList.size() > 0) { for (int i = 0; i < annoList.size(); i++) { smali.startLine(); writeAnnotation(smali, annoList.get(i)); if (i != annoList.size() - 1) { smali.startLine(); } } } } private void writeAnnotation(SmaliWriter smali, IAnnotation anno) { smali.add(".annotation") .add(" "); AnnotationVisibility vby = anno.getVisibility(); if (vby != null) { smali.add(vby.toString().toLowerCase()).add(" "); } smali.add(anno.getAnnotationClass()); anno.getValues().forEach((k, v) -> { smali.incIndent(); smali.startLine(k).add(" = "); writeEncodedValue(smali, v, true); smali.decIndent(); }); smali.startLine(".end annotation"); } private void formatDbgInfo(IDebugInfo dbgInfo, List<ILocalVar> localVars, LineInfo line) { dbgInfo.getSourceLineMapping().forEach((codeOffset, srcLine) -> { if (codeOffset > -1) { line.addDebugLineTip(codeOffset, String.format(".line %d", srcLine), ""); } }); for (ILocalVar localVar : localVars) { if (localVar.isMarkedAsParameter()) { continue; } String type = localVar.getType(); String sign = localVar.getSignature(); String longTypeStr; if (sign == null || sign.trim().isEmpty()) { longTypeStr = String.format(", \"%s\":%s", localVar.getName(), type); } else { longTypeStr = String.format(", \"%s\":%s, \"%s\"", localVar.getName(), type, localVar.getSignature()); } line.addTip( localVar.getStartOffset(), ".local " + formatVarName(line.smaliMthNode, localVar), longTypeStr); line.addTip( localVar.getEndOffset(), ".end local " + formatVarName(line.smaliMthNode, localVar), String.format(" # \"%s\":%s", localVar.getName(), type)); } } private String formatVarName(SmaliMethodNode smaliMthNode, ILocalVar localVar) { int paramRegStart = smaliMthNode.getParamRegStart(); int regNum = localVar.getRegNum(); if (regNum < paramRegStart) { return "v" + regNum; } return "p" + (regNum - paramRegStart); } private void writeEncodedValue(SmaliWriter smali, EncodedValue value, boolean wrapArray) { StringUtils stringUtils = smali.getClassNode().root().getStringUtils(); switch (value.getType()) { case ENCODED_ARRAY: smali.add("{"); if (wrapArray) { smali.incIndent(); smali.startLine(); } List<EncodedValue> values = (List<EncodedValue>) value.getValue(); for (int i = 0; i < values.size(); i++) { writeEncodedValue(smali, values.get(i), wrapArray); if (i != values.size() - 1) { smali.add(","); if (wrapArray) { smali.startLine(); } else { smali.add(" "); } } } if (wrapArray) { smali.decIndent(); smali.startLine("}"); } break; case ENCODED_NULL: smali.add("null"); break; case ENCODED_ANNOTATION: writeAnnotation(smali, (IAnnotation) value.getValue()); break; case ENCODED_BYTE: smali.add(stringUtils.formatByte((Byte) value.getValue(), false)); break; case ENCODED_SHORT: smali.add(stringUtils.formatShort((Short) value.getValue(), false)); break; case ENCODED_CHAR: smali.add(stringUtils.unescapeChar((Character) value.getValue())); break; case ENCODED_INT: smali.add(stringUtils.formatInteger((Integer) value.getValue(), false)); break; case ENCODED_LONG: smali.add(stringUtils.formatLong((Long) value.getValue(), false)); break; case ENCODED_FLOAT: smali.add(StringUtils.formatFloat((Float) value.getValue())); break; case ENCODED_DOUBLE: smali.add(StringUtils.formatDouble((Double) value.getValue())); break; case ENCODED_STRING: smali.add(stringUtils.unescapeString((String) value.getValue())); break; case ENCODED_TYPE: smali.add(ArgType.parse((String) value.getValue()) + ".class"); break; default: smali.add(String.valueOf(value.getValue())); } } private static final int CODE_OFFSET_COLUMN_WIDTH = 4; private static final int BYTECODE_COLUMN_WIDTH = 20 + 3; // 3 for ellipses. private static final String FMT_BYTECODE_COL = "%-" + (BYTECODE_COLUMN_WIDTH - 3) + "s"; private static final int INSN_COL_WIDTH = "const-method-handle".length(); private static final String FMT_INSN_COL = "%-" + INSN_COL_WIDTH + "s"; private static final String FMT_FILE_OFFSET = "%08x:"; private static final String FMT_CODE_OFFSET = "%04x:"; private static final String FMT_TARGET_OFFSET = "%04x"; private static final String FMT_GOTO = ":goto_" + FMT_TARGET_OFFSET; private static final String FMT_COND = ":cond_" + FMT_TARGET_OFFSET; private static final String FMT_DATA = ":array_" + FMT_TARGET_OFFSET; private static final String FMT_P_SWITCH = ":p_switch_" + FMT_TARGET_OFFSET; private static final String FMT_S_SWITCH = ":s_switch_" + FMT_TARGET_OFFSET; private static final String FMT_P_SWITCH_CASE = ":p_case_" + FMT_TARGET_OFFSET; private static final String FMT_S_SWITCH_CASE = ":s_case_" + FMT_TARGET_OFFSET; private static final String FMT_TRY_TAG = "try_" + FMT_TARGET_OFFSET + ":"; private static final String FMT_TRY_END_TAG = "try_end_" + FMT_TARGET_OFFSET + ":"; private static final String FMT_CATCH_TAG = "catch_" + FMT_TARGET_OFFSET + ":"; private static final String FMT_CATCH_ALL_TAG = "catch_all_" + FMT_TARGET_OFFSET + ":"; private static final String FMT_GOTO_TAG = "goto_" + FMT_TARGET_OFFSET + ":"; private static final String FMT_COND_TAG = "cond_" + FMT_TARGET_OFFSET + ":"; private static final String FMT_DATA_TAG = "array_" + FMT_TARGET_OFFSET + ":"; private static final String FMT_P_SWITCH_TAG = "p_switch_" + FMT_TARGET_OFFSET + ":"; private static final String FMT_S_SWITCH_TAG = "s_switch_" + FMT_TARGET_OFFSET + ":"; private static final String FMT_P_SWITCH_CASE_TAG = "p_case_" + FMT_TARGET_OFFSET + ":"; private static final String FMT_S_SWITCH_CASE_TAG = "s_case_" + FMT_TARGET_OFFSET + ":"; private void fmtRegs(InsnData insn, InsnType insnType, LineInfo line) { boolean appendBrace = insnType == InsnType.INVOKE || isRegList(insn); StringBuilder lw = line.getLineWriter(); if (insnType == InsnType.INVOKE) { int resultReg = insn.getResultReg(); if (resultReg != -1) { lw.append(line.getRegName(resultReg)).append(" <= "); } } if (appendBrace) { lw.append("{"); } if (isRangeRegIns(insn)) { lw.append(line.getRegName(insn.getReg(0))) .append(" .. ") .append(line.getRegName(insn.getReg(insn.getRegsCount() - 1))); } else if (insn.getRegsCount() > 0) { for (int i = 0; i < insn.getRegsCount(); i++) { if (i > 0) { lw.append(", "); } lw.append(line.getRegName(insn.getReg(i))); } } if (appendBrace) { lw.append("}"); } } private int getInsnColStart() { int start = 0; if (printFileOffset) { start += 8 + 1 + 1; // plus 1s for space and the ':' } if (printBytecode) { start += BYTECODE_COLUMN_WIDTH + 1; // plus 1 for space } return start; } private void fmtCols(InsnData insn, LineInfo line) { if (printFileOffset) { line.getLineWriter().append(String.format(FMT_FILE_OFFSET + " ", insn.getFileOffset())); } if (printBytecode) { formatByteCode(line.getLineWriter(), insn.getByteCode()); line.getLineWriter().append(" "); line.getLineWriter().append(String.format(FMT_CODE_OFFSET + " ", insn.getOffset())); } } private void formatByteCode(StringBuilder smali, byte[] bytes) { int maxLen = Math.min(bytes.length, 4 * 2); // limit to 4 units StringBuilder inHex = new StringBuilder(); for (int i = 0; i < maxLen; i++) { inHex.append(String.format("%02x", bytes[i])); if (i % 2 == 1) { inHex.append(' '); } } smali.append(String.format(FMT_BYTECODE_COL, inHex)); if (maxLen < bytes.length) { smali.append("..."); } else { smali.append(" "); } } private boolean fmtPayloadInsn(InsnData insn, LineInfo line) { Opcode opcode = insn.getOpcode(); if (opcode == PACKED_SWITCH_PAYLOAD) { line.getLineWriter().append("packed-switch-payload"); line.addInsnLine(insn.getOffset(), line.getLineWriter().toString()); ISwitchPayload payload = (ISwitchPayload) insn.getPayload(); if (payload != null) { fmtSwitchPayload(insn, FMT_P_SWITCH_CASE, FMT_P_SWITCH_CASE_TAG, line, payload); } return true; } if (opcode == SPARSE_SWITCH_PAYLOAD) { line.getLineWriter().append("sparse-switch-payload"); line.addInsnLine(insn.getOffset(), line.getLineWriter().toString()); ISwitchPayload payload = (ISwitchPayload) insn.getPayload(); if (payload != null) { fmtSwitchPayload(insn, FMT_S_SWITCH_CASE, FMT_S_SWITCH_CASE_TAG, line, payload); } return true; } if (opcode == FILL_ARRAY_DATA_PAYLOAD) { line.getLineWriter().append("fill-array-data-payload"); line.addInsnLine(insn.getOffset(), line.getLineWriter().toString()); return true; } return false; } private void fmtSwitchPayload(InsnData insn, String fmtTarget, String fmtTag, LineInfo line, ISwitchPayload payload) { int lineStart = getInsnColStart(); lineStart += CODE_OFFSET_COLUMN_WIDTH + 1 + 1; // plus 1s for space and the ':' String basicIndent = new String(new byte[lineStart]).replace("\0", " "); String indent = JadxArgs.DEFAULT_INDENT_STR + basicIndent; int[] keys = payload.getKeys(); int[] targets = payload.getTargets(); Integer switchOffset = line.payloadOffsetMap.get(insn.getOffset()); if (switchOffset == null) { throw new JadxRuntimeException("Unknown switch insn for payload at " + insn.getOffset()); } for (int i = 0; i < keys.length; i++) { int target = switchOffset + targets[i]; line.addInsnLine(insn.getOffset(), String.format("%scase %d: -> " + fmtTarget, indent, keys[i], target)); line.addTip(target, String.format(fmtTag, target), String.format(" # case %d", keys[i])); } line.addInsnLine(insn.getOffset(), basicIndent + ".end payload"); } private static String literal(InsnData insn) { long it = insn.getLiteral(); String tip = ""; if (it > Integer.MAX_VALUE) { if (isWideIns(insn)) { tip = " # double: " + Double.longBitsToDouble(it); } else if (getOpenCodeByte(insn) == 0x15) { // CONST_HIGH16 = 0x15; tip = " # float: " + Float.intBitsToFloat((int) it); } } else if (it <= 0) { return "" + it + tip; } return "0x" + Long.toHexString(it) + tip; } private static String str(InsnData insn) { return String.format("\"%s\" # string@%04x", insn.getIndexAsString() .replace("\n", "\\n") .replace("\t", "\\t"), insn.getIndex()); } private static String type(InsnData insn) { return String.format("%s # type@%04x", insn.getIndexAsType(), insn.getIndex()); } private static String field(InsnData insn) { return String.format("%s # field@%04x", insn.getIndexAsField().toString(), insn.getIndex()); } private static String method(InsnData insn) { Opcode op = insn.getOpcode(); if (op == INVOKE_CUSTOM || op == INVOKE_CUSTOM_RANGE) { insn.getIndexAsCallSite().load(); return String.format("%s # call_site@%04x", insn.getIndexAsCallSite().toString(), insn.getIndex()); } IMethodRef mthRef = insn.getIndexAsMethod(); mthRef.load(); if (op == INVOKE_POLYMORPHIC || op == INVOKE_POLYMORPHIC_RANGE) { return String.format("%s, %s # method@%04x, proto@%04x", mthRef.toString(), insn.getIndexAsProto(insn.getTarget()).toString(), insn.getIndex(), insn.getTarget()); } return String.format("%s # method@%04x", mthRef.toString(), insn.getIndex()); } private static String proto(InsnData insn, int protoIndex) { return String.format("%s # proto@%04x", insn.getIndexAsProto(protoIndex).toString(), protoIndex); } private static String methodHandle(InsnData insn) { return String.format("%s # method_handle@%04x", insn.getIndexAsMethodHandle().toString(), insn.getIndex()); } protected static boolean isRangeRegIns(InsnData insn) { switch (insn.getOpcode()) { case INVOKE_VIRTUAL_RANGE: case INVOKE_SUPER_RANGE: case INVOKE_DIRECT_RANGE: case INVOKE_STATIC_RANGE: case INVOKE_INTERFACE_RANGE: case FILLED_NEW_ARRAY_RANGE: case INVOKE_CUSTOM_RANGE: case INVOKE_POLYMORPHIC_RANGE: return true; } return false; } private static int getOpenCodeByte(InsnData insn) { return insn.getRawOpcodeUnit() & 0xff; } private static boolean isWideIns(InsnData insn) { return insn.getOpcode() == CONST_WIDE; } private static boolean hasLiteral(InsnData insn) { int opcode = getOpenCodeByte(insn); return insn.getOpcode() == CONST || insn.getOpcode() == CONST_WIDE || (opcode >= 0xd0 && opcode <= 0xe2); // add-int/lit16 to ushr-int/lit8 } private static boolean isRegList(InsnData insn) { return insn.getOpcode() == FILLED_NEW_ARRAY || insn.getOpcode() == FILLED_NEW_ARRAY_RANGE; } private class LineInfo { private SmaliMethodNode smaliMthNode = new SmaliMethodNode(); private final StringBuilder lineWriter = new StringBuilder(50); private String lastDebugTip = ""; private final Map<Integer, List<String>> insnOffsetMap = new LinkedHashMap<>(); private final Map<Integer, String> regNameMap = new HashMap<>(); private Map<Integer, Map<String, Object>> tipMap = Collections.emptyMap(); private Map<Integer, Integer> payloadOffsetMap = Collections.emptyMap(); public LineInfo() { } public StringBuilder getLineWriter() { return lineWriter; } public void reset() { lastDebugTip = ""; payloadOffsetMap = Collections.emptyMap(); tipMap = Collections.emptyMap(); insnOffsetMap.clear(); regNameMap.clear(); smaliMthNode = new SmaliMethodNode(); } public void addRegName(int regNum, String name) { regNameMap.put(regNum, name); } public String getRegName(int regNum) { String name = regNameMap.get(regNum); if (name == null) { name = "v" + regNum; } return name; } public void addInsnLine(int codeOffset, String insnLine) { List<String> insnList = insnOffsetMap.computeIfAbsent(codeOffset, k -> new ArrayList<>(1)); insnList.add(insnLine); } public void addTip(int offset, String tip, String extra) { if (tipMap.isEmpty()) { tipMap = new LinkedHashMap<>(); } Map<String, Object> innerMap = tipMap.computeIfAbsent(offset, k -> new LinkedHashMap<>());
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
true
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/debugger/smali/SmaliMethodNode.java
jadx-gui/src/main/java/jadx/gui/device/debugger/smali/SmaliMethodNode.java
package jadx.gui.device.debugger.smali; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import jadx.core.dex.instructions.args.InsnArg; import jadx.core.dex.instructions.args.RegisterArg; import jadx.core.dex.nodes.InsnNode; class SmaliMethodNode { private Map<Long, InsnNode> nodes; // codeOffset: InsnNode private List<SmaliRegister> regList; private int[] insnPos; private int defPos; private Map<Integer, Integer> lineMapping = Collections.emptyMap(); // line: codeOffset private int paramRegStart; private int regCount; public int getParamRegStart() { return this.paramRegStart; } public int getRegCount() { return this.regCount; } public Map<Integer, Integer> getLineMapping() { return lineMapping; } public void initRegInfoList(int regCount, int insnCount) { regList = new ArrayList<>(regCount); for (int i = 0; i < regCount; i++) { regList.add(new SmaliRegister(i, insnCount)); } } public int getInsnPos(long codeOffset) { if (insnPos != null && codeOffset < insnPos.length) { return insnPos[(int) codeOffset]; } return -1; } public int getDefPos() { return defPos; } public InsnNode getInsnNode(long codeOffset) { return nodes.get(codeOffset); } public List<SmaliRegister> getRegList() { return regList; } protected SmaliMethodNode() { } protected void setRegCount(int regCount) { this.regCount = regCount; } protected void attachLine(int line, int codeOffset) { if (lineMapping.isEmpty()) { lineMapping = new HashMap<>(); } lineMapping.put(line, codeOffset); } protected void setInsnInfo(int codeOffset, int pos) { if (insnPos != null && codeOffset < insnPos.length) { insnPos[codeOffset] = pos; } InsnNode insn = getInsnNode(codeOffset); RegisterArg r = insn.getResult(); if (r != null) { regList.get(r.getRegNum()).setStartOffset(codeOffset); } for (InsnArg arg : insn.getArguments()) { if (arg instanceof RegisterArg) { regList.get(((RegisterArg) arg).getRegNum()).setStartOffset(codeOffset); } } } protected void setDefPos(int pos) { defPos = pos; } protected void setParamReg(int regNum, String name) { SmaliRegister r = regList.get(regNum); r.setParam(name); } protected void setParamRegStart(int paramRegStart) { this.paramRegStart = paramRegStart; } protected void setInsnNodes(Map<Long, InsnNode> nodes, int insnCount) { this.nodes = nodes; insnPos = new int[insnCount]; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/protocol/ADBDevice.java
jadx-gui/src/main/java/jadx/gui/device/protocol/ADBDevice.java
package jadx.gui.device.protocol; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Executors; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.utils.StringUtils; import jadx.core.utils.log.LogUtils; import jadx.gui.device.protocol.ADB.JDWPProcessListener; import jadx.gui.device.protocol.ADB.Process; public class ADBDevice { private static final Logger LOG = LoggerFactory.getLogger(ADBDevice.class); private static final String CMD_TRACK_JDWP = "000atrack-jdwp"; private static final Pattern TIMESTAMP_FORMAT = Pattern.compile("^[0-9]{2}\\-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}$"); ADBDeviceInfo info; String androidReleaseVer; volatile Socket jdwpListenerSock; public ADBDevice(ADBDeviceInfo info) { this.info = info; } public ADBDeviceInfo getDeviceInfo() { return info; } public boolean updateDeviceInfo(ADBDeviceInfo info) { if (info.getSerial() == null || info.getSerial().isEmpty()) { return false; } boolean matched = this.info.getSerial().equals(info.getSerial()); if (matched) { this.info = info; } return matched; } public String getSerial() { return info.getSerial(); } public boolean removeForward(String localPort) throws IOException { return ADB.removeForward(info.getAdbHost(), info.getAdbPort(), info.getSerial(), localPort); } public ForwardResult forwardJDWP(String localPort, String jdwpPid) throws IOException { try (Socket socket = ADB.connect(info.getAdbHost(), info.getAdbPort())) { String cmd = String.format("host:forward:tcp:%s;jdwp:%s", localPort, jdwpPid); cmd = String.format("%04x%s", cmd.length(), cmd); InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); ForwardResult rst; if (ADB.setSerial(info.getSerial(), outputStream, inputStream)) { outputStream.write(cmd.getBytes()); if (!ADB.isOkay(inputStream)) { rst = new ForwardResult(1, ADB.readServiceProtocol(inputStream)); } else if (!ADB.isOkay(inputStream)) { rst = new ForwardResult(2, ADB.readServiceProtocol(inputStream)); } else { rst = new ForwardResult(0, null); } } else { rst = new ForwardResult(1, "Unknown error.".getBytes()); } return rst; } } public static class ForwardResult { /** * 0 for success, 1 for failed at binding to local tcp, 2 for failed at remote. */ public int state; public String desc; public ForwardResult(int state, byte[] desc) { if (desc != null) { this.desc = new String(desc); } else { this.desc = ""; } this.state = state; } } /** * @return pid otherwise -1 */ public int launchApp(String fullAppName) throws IOException, InterruptedException { byte[] res; try (Socket socket = ADB.connect(info.getAdbHost(), info.getAdbPort())) { String cmd = "am start -D -n " + fullAppName; res = ADB.execShellCommandRaw(info.getSerial(), cmd, socket.getOutputStream(), socket.getInputStream()); if (res == null) { return -1; } } String rst = new String(res).trim(); if (rst.startsWith("Starting: Intent {") && rst.endsWith(fullAppName + " }")) { Thread.sleep(40); String pkg = fullAppName.split("/")[0]; for (Process process : getProcessByPkg(pkg)) { return Integer.parseInt(process.pid); } } return -1; } /** * @return binary output of logcat */ public byte[] getBinaryLogcat() throws IOException { Socket socket = ADB.connect(info.getAdbHost(), info.getAdbPort()); String cmd = "logcat -dB"; return ADB.execShellCommandRaw(info.getSerial(), cmd, socket.getOutputStream(), socket.getInputStream()); } /** * @return binary output of logcat after provided timestamp * Timestamp is in the format 09-08 02:18:03.131 */ public byte[] getBinaryLogcat(String timestamp) throws IOException { Socket socket = ADB.connect(info.getAdbHost(), info.getAdbPort()); Matcher matcher = TIMESTAMP_FORMAT.matcher(timestamp); if (!matcher.find()) { LOG.error("Invalid Logcat Timestamp " + timestamp); } String cmd = "logcat -dB -t \"" + timestamp + "\""; return ADB.execShellCommandRaw(info.getSerial(), cmd, socket.getOutputStream(), socket.getInputStream()); } /** * Binary output of logcat -c */ public void clearLogcat() throws IOException { Socket socket = ADB.connect(info.getAdbHost(), info.getAdbPort()); String cmd = "logcat -c"; ADB.execShellCommandRaw(info.getSerial(), cmd, socket.getOutputStream(), socket.getInputStream()); } /** * @return Timezone for the attached android device */ public String getTimezone() throws IOException { Socket socket = ADB.connect(info.getAdbHost(), info.getAdbPort()); String cmd = "getprop persist.sys.timezone"; byte[] tz = ADB.execShellCommandRaw(info.getSerial(), cmd, socket.getOutputStream(), socket.getInputStream()); return new String(tz).trim(); } public String getAndroidReleaseVersion() { if (!StringUtils.isEmpty(androidReleaseVer)) { return androidReleaseVer; } try { List<String> list = getProp("ro.build.version.release"); if (list.size() != 0) { androidReleaseVer = list.get(0); } } catch (Exception e) { LOG.error("Failed to get android release version", e); androidReleaseVer = ""; } return androidReleaseVer; } public List<String> getProp(String entry) throws IOException { try (Socket socket = ADB.connect(info.getAdbHost(), info.getAdbPort())) { List<String> props = Collections.emptyList(); String cmd = "getprop"; if (!StringUtils.isEmpty(entry)) { cmd += " " + entry; } byte[] payload = ADB.execShellCommandRaw(info.getSerial(), cmd, socket.getOutputStream(), socket.getInputStream()); if (payload != null) { props = new ArrayList<>(); String[] lines = new String(payload).split("\n"); for (String line : lines) { line = line.trim(); if (!line.isEmpty()) { props.add(line); } } } return props; } } public List<Process> getProcessByPkg(String pkg) throws IOException { return getProcessList("ps | grep " + pkg); } public List<Process> getProcessList() throws IOException { return getProcessList("ps"); } private List<Process> getProcessList(String cmd) throws IOException { try (Socket socket = ADB.connect(info.getAdbHost(), info.getAdbPort())) { List<Process> procs = new ArrayList<>(); byte[] payload = ADB.execShellCommandRaw(info.getSerial(), cmd, socket.getOutputStream(), socket.getInputStream()); if (payload != null) { String ps = new String(payload); String[] psLines = ps.split("\n"); for (String line : psLines) { line = line.trim(); if (line.isEmpty()) { continue; } Process proc = Process.make(line); if (proc != null) { procs.add(proc); } else { LOG.error("Unexpected process info data received: \"{}\"", LogUtils.escape(line)); } } } return procs; } } public boolean listenForJDWP(JDWPProcessListener listener) throws IOException { if (this.jdwpListenerSock != null) { return false; } jdwpListenerSock = ADB.connect(this.info.getAdbHost(), this.info.getAdbPort()); InputStream inputStream = jdwpListenerSock.getInputStream(); OutputStream outputStream = jdwpListenerSock.getOutputStream(); if (ADB.setSerial(info.getSerial(), outputStream, inputStream) && ADB.execCommandAsync(outputStream, inputStream, CMD_TRACK_JDWP)) { Executors.newFixedThreadPool(1).execute(() -> { for (;;) { byte[] res = ADB.readServiceProtocol(inputStream); if (res != null) { if (listener != null) { String payload = new String(res); String[] ids = payload.split("\n"); Set<String> idList = new HashSet<>(ids.length); for (String id : ids) { if (!id.trim().isEmpty()) { idList.add(id); } } listener.jdwpProcessOccurred(this, idList); } } else { // socket disconnected break; } } if (listener != null) { this.jdwpListenerSock = null; listener.jdwpListenerClosed(this); } }); } else { jdwpListenerSock.close(); jdwpListenerSock = null; return false; } return true; } public void stopListenForJDWP() { if (jdwpListenerSock != null) { try { jdwpListenerSock.close(); } catch (Exception e) { LOG.error("JDWP socket close failed", e); } } this.jdwpListenerSock = null; } @Override public int hashCode() { return info.getSerial().hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof ADBDevice) { String otherSerial = ((ADBDevice) obj).getDeviceInfo().getSerial(); return otherSerial.equals(info.getSerial()); } return false; } @Override public String toString() { return info.getAllInfo(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/protocol/ADB.java
jadx-gui/src/main/java/jadx/gui/device/protocol/ADB.java
package jadx.gui.device.protocol; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.utils.log.LogUtils; import jadx.gui.utils.IOUtils; public class ADB { private static final Logger LOG = LoggerFactory.getLogger(ADB.class); private static final int DEFAULT_PORT = 5037; private static final String DEFAULT_ADDR = "localhost"; private static final String CMD_FEATURES = "000dhost:features"; private static final String CMD_TRACK_DEVICES = "0014host:track-devices-l"; private static final byte[] OKAY = "OKAY".getBytes(); private static final byte[] FAIL = "FAIL".getBytes(); static boolean isOkay(InputStream stream) throws IOException { byte[] buf = IOUtils.readNBytes(stream, 4); if (Arrays.equals(buf, OKAY)) { return true; } if (Arrays.equals(buf, FAIL)) { // Observed that after FAIL the length in hex follows and afterwards an error message, // but it is unclear if this is true for all cases where isOkay is used. // int msgLen = Integer.parseInt(new String(IOUtils.readNBytes(stream, 4)), 16); // byte[] errorMsg = IOUtils.readNBytes(stream, msgLen); // LOG.error("isOkay failed: received error message: {}", new String(errorMsg)); LOG.error("isOkay failed"); return false; } if (buf == null) { throw new IOException("isOkay failed - steam ended"); } throw new IOException("isOkay failed - unexpected response " + new String(buf)); } public static byte[] exec(String cmd, OutputStream outputStream, InputStream inputStream) throws IOException { return execCommandSync(outputStream, inputStream, cmd); } public static byte[] exec(String cmd) throws IOException { try (Socket socket = connect()) { return exec(cmd, socket.getOutputStream(), socket.getInputStream()); } } public static Socket connect() throws IOException { return connect(DEFAULT_ADDR, DEFAULT_PORT); } public static Socket connect(String host, int port) throws IOException { return new Socket(host, port); } static boolean execCommandAsync(OutputStream outputStream, InputStream inputStream, String cmd) throws IOException { outputStream.write(cmd.getBytes()); return isOkay(inputStream); } private static byte[] execCommandSync(OutputStream outputStream, InputStream inputStream, String cmd) throws IOException { outputStream.write(cmd.getBytes()); if (isOkay(inputStream)) { return readServiceProtocol(inputStream); } return null; } static byte[] readServiceProtocol(InputStream stream) { try { byte[] buf = IOUtils.readNBytes(stream, 4); if (buf == null) { return null; } int len = unhex(buf); byte[] result; if (len == 0) { result = new byte[0]; } else { result = IOUtils.readNBytes(stream, len); } if (LOG.isTraceEnabled()) { LOG.trace("readServiceProtocol result: {}", LogUtils.escape(result)); } return result; } catch (SocketException e) { LOG.warn("Aborting readServiceProtocol: {}", e.toString()); } catch (IOException e) { LOG.error("Failed to read readServiceProtocol", e); } return null; } static boolean setSerial(String serial, OutputStream outputStream, InputStream inputStream) throws IOException { String setSerialCmd = String.format("host:tport:serial:%s", serial); setSerialCmd = String.format("%04x%s", setSerialCmd.length(), setSerialCmd); outputStream.write(setSerialCmd.getBytes()); boolean ok = isOkay(inputStream); if (ok) { // skip the shell-state-id returned by ADB server, it's not important for the following actions. IOUtils.readNBytes(inputStream, 8); } else { LOG.error("setSerial command {} failed", LogUtils.escape(setSerialCmd)); } return ok; } private static byte[] execShellCommandRaw(String cmd, OutputStream outputStream, InputStream inputStream) throws IOException { cmd = String.format("shell,v2,TERM=xterm-256color,raw:%s", cmd); cmd = String.format("%04x%s", cmd.length(), cmd); outputStream.write(cmd.getBytes()); if (isOkay(inputStream)) { return ShellProtocol.readStdout(inputStream); } return null; } static byte[] execShellCommandRaw(String serial, String cmd, OutputStream outputStream, InputStream inputStream) throws IOException { if (setSerial(serial, outputStream, inputStream)) { return execShellCommandRaw(cmd, outputStream, inputStream); } return null; } public static List<String> getFeatures() throws IOException { byte[] rst = exec(CMD_FEATURES); if (rst != null) { return Arrays.asList(new String(rst).trim().split(",")); } return Collections.emptyList(); } public static boolean startServer(String adbPath, int port) throws IOException { String tcpPort = String.format("tcp:%d", port); List<String> command = Arrays.asList(adbPath, "-L", tcpPort, "start-server"); java.lang.Process proc = new ProcessBuilder(command) .redirectErrorStream(true) .start(); try { // Wait for the adb server to start. On Windows even on a fast system 6 seconds are not unusual. proc.waitFor(10, TimeUnit.SECONDS); proc.exitValue(); } catch (Exception e) { LOG.error("ADB start server failed with command: {}", String.join(" ", command), e); proc.destroyForcibly(); return false; } ByteArrayOutputStream out = new ByteArrayOutputStream(); try (InputStream in = proc.getInputStream()) { int read; byte[] buf = new byte[1024]; while ((read = in.read(buf)) >= 0) { out.write(buf, 0, read); } } return out.toString().contains(tcpPort); } public static boolean isServerRunning(String host, int port) { try (Socket sock = new Socket(host, port)) { return true; } catch (Exception e) { return false; } } /** * @return a socket connected to adb server, otherwise null */ public static Socket listenForDeviceState(DeviceStateListener listener, String host, int port) throws IOException { Socket socket = connect(host, port); InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); if (!execCommandAsync(outputStream, inputStream, CMD_TRACK_DEVICES)) { socket.close(); return null; } ExecutorService listenThread = Executors.newFixedThreadPool(1); listenThread.execute(() -> { while (true) { byte[] res = readServiceProtocol(inputStream); if (res == null) { break; // socket disconnected } if (listener != null) { String payload = new String(res); String[] deviceLines = payload.split("\n"); List<ADBDeviceInfo> deviceInfoList = new ArrayList<>(deviceLines.length); for (String deviceLine : deviceLines) { if (!deviceLine.trim().isEmpty()) { deviceInfoList.add(new ADBDeviceInfo(deviceLine, host, port)); } } listener.onDeviceStatusChange(deviceInfoList); } } if (listener != null) { listener.adbDisconnected(); } }); return socket; } public static List<String> listForward(String host, int port) throws IOException { try (Socket socket = connect(host, port)) { String cmd = "0011host:list-forward"; InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); outputStream.write(cmd.getBytes()); if (isOkay(inputStream)) { byte[] bytes = readServiceProtocol(inputStream); if (bytes != null) { String[] forwards = new String(bytes).split("\n"); return Stream.of(forwards).map(String::trim).collect(Collectors.toList()); } } } return Collections.emptyList(); } public static boolean removeForward(String host, int port, String serial, String localPort) throws IOException { try (Socket socket = connect(host, port)) { String cmd = String.format("host:killforward:tcp:%s", localPort); cmd = String.format("%04x%s", cmd.length(), cmd); InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); if (setSerial(serial, outputStream, inputStream)) { outputStream.write(cmd.getBytes()); return isOkay(inputStream) && isOkay(inputStream); } } return false; } // Little endian private static int readInt(byte[] bytes, int start) { int result = (bytes[start] & 0xff); result += ((bytes[start + 1] & 0xff) << 8); result += ((bytes[start + 2] & 0xff) << 16); result += (bytes[start + 3] & 0xff) << 24; return result; } private static byte[] appendBytes(byte[] dest, byte[] src, int realSrcSize) { byte[] rst = new byte[dest.length + realSrcSize]; System.arraycopy(dest, 0, rst, 0, dest.length); System.arraycopy(src, 0, rst, dest.length, realSrcSize); return rst; } private static int unhex(byte[] hex) { int n = 0; byte b; for (int i = 0; i < 4; i++) { b = hex[i]; switch (b) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': b -= '0'; break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': b = (byte) (b - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': b = (byte) (b - 'A' + 10); break; default: return -1; } n = (n << 4) | (b & 0xff); } return n; } public interface JDWPProcessListener { void jdwpProcessOccurred(ADBDevice device, Set<String> id); void jdwpListenerClosed(ADBDevice device); } public interface DeviceStateListener { void onDeviceStatusChange(List<ADBDeviceInfo> deviceInfoList); void adbDisconnected(); } public static class Process { public String user; public String pid; public String ppid; public String name; public static Process make(String processLine) { String[] fields = processLine.split("\\s+"); if (fields.length >= 4) { // 0 for user, 1 for pid, 2 for ppid, the last one for name Process proc = new Process(); proc.user = fields[0]; proc.pid = fields[1]; proc.ppid = fields[2]; proc.name = fields[fields.length - 1]; return proc; } return null; } } private static class ShellProtocol { private static final int ID_STD_IN = 0; private static final int ID_STD_OUT = 1; private static final int ID_STD_ERR = 2; private static final int ID_EXIT = 3; // Close subprocess stdin if possible. private static final int ID_CLOSE_STDIN = 4; // Window size change (an ASCII version of struct winsize). private static final int ID_WINDOW_SIZE_CHANGE = 5; // Indicates an invalid or unknown packet. private static final int ID_INVALID = 255; public static byte[] readStdout(InputStream inputStream) throws IOException { byte[] header = new byte[5]; ByteArrayOutputStream payload = new ByteArrayOutputStream(); byte[] tempBuf = new byte[1024]; for (boolean exit = false; !exit;) { IOUtils.read(inputStream, header); exit = header[0] == ID_EXIT; int payloadSize = readInt(header, 1); if (tempBuf.length < payloadSize) { tempBuf = new byte[payloadSize]; } int readSize = IOUtils.read(inputStream, tempBuf, 0, payloadSize); if (readSize != payloadSize) { LOG.error("Failed to read ShellProtocol data"); return null; // we don't want corrupted data. } payload.write(tempBuf, 0, readSize); } return payload.toByteArray(); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/device/protocol/ADBDeviceInfo.java
jadx-gui/src/main/java/jadx/gui/device/protocol/ADBDeviceInfo.java
package jadx.gui.device.protocol; import java.util.Map; import java.util.TreeMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.utils.log.LogUtils; public class ADBDeviceInfo { private static final Logger LOG = LoggerFactory.getLogger(ADBDeviceInfo.class); private final String adbHost; private final int adbPort; private final String serial; private final String state; private final String model; private final String allInfo; /** * Store the device info property values like "device" "model" "product" or "transport_id" */ private final Map<String, String> propertiesMap = new TreeMap<>(); ADBDeviceInfo(String info, String host, int port) { String[] infoFields = info.trim().split("\\s+"); allInfo = String.join(" ", infoFields); if (infoFields.length > 2) { serial = infoFields[0]; state = infoFields[1]; for (int i = 2; i < infoFields.length; i++) { String field = infoFields[i]; int idx = field.indexOf(':'); if (idx > 0) { String key = field.substring(0, idx); String value = field.substring(idx + 1); if (!value.isEmpty()) { propertiesMap.put(key, value); } } } model = propertiesMap.getOrDefault("model", serial); } else { LOG.error("Unable to extract device information from {}", LogUtils.escape(info)); serial = ""; state = "unknown"; model = "unknown"; } adbHost = host; adbPort = port; } public boolean isOnline() { return state.equals("device"); } public String getAdbHost() { return adbHost; } public int getAdbPort() { return adbPort; } public String getSerial() { return serial; } public String getState() { return state; } public String getModel() { return model; } public String getAllInfo() { return allInfo; } public String getProperty(String key) { return this.propertiesMap.get(key); } @Override public String toString() { return allInfo; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/CodeStringCache.java
jadx-gui/src/main/java/jadx/gui/cache/code/CodeStringCache.java
package jadx.gui.cache.code; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.reactivestreams.Subscriber; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.processors.PublishProcessor; import jadx.api.ICodeCache; import jadx.api.ICodeInfo; import jadx.api.impl.DelegateCodeCache; import jadx.gui.utils.UiUtils; /** * Keep code strings for faster search */ public class CodeStringCache extends DelegateCodeCache { private static final Logger LOG = LoggerFactory.getLogger(CodeStringCache.class); private final Map<String, String> codeCache = new ConcurrentHashMap<>(); private final Subscriber<Boolean> subscriber; private final Disposable disposable; public CodeStringCache(ICodeCache backCache) { super(backCache); // reset cache if free memory is low // check only on changes (with debounce) to reduce background checks if app not used PublishProcessor<Boolean> processor = PublishProcessor.create(); subscriber = processor; disposable = processor.debounce(3, TimeUnit.SECONDS) .map(v -> UiUtils.isFreeMemoryAvailable()) .filter(v -> !v) .subscribe(v -> { LOG.warn("Free memory is low! Reset code strings cache. Cache size {}", codeCache.size()); codeCache.clear(); System.gc(); }); } @Override @Nullable public String getCode(String clsFullName) { subscriber.onNext(Boolean.TRUE); String code = codeCache.get(clsFullName); if (code != null) { return code; } String backCode = backCache.getCode(clsFullName); if (backCode != null) { codeCache.put(clsFullName, backCode); } return backCode; } @Override public @NotNull ICodeInfo get(String clsFullName) { subscriber.onNext(Boolean.TRUE); return super.get(clsFullName); } @Override public void add(String clsFullName, ICodeInfo codeInfo) { subscriber.onNext(Boolean.TRUE); codeCache.put(clsFullName, codeInfo.getCodeStr()); backCache.add(clsFullName, codeInfo); } @Override public void remove(String clsFullName) { codeCache.remove(clsFullName); backCache.remove(clsFullName); } @Override public void close() throws IOException { try { backCache.close(); } finally { codeCache.clear(); subscriber.onComplete(); disposable.dispose(); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/CodeCacheMode.java
jadx-gui/src/main/java/jadx/gui/cache/code/CodeCacheMode.java
package jadx.gui.cache.code; import java.util.stream.Collectors; import java.util.stream.Stream; // TODO: use localized strings public enum CodeCacheMode { MEMORY("Everything in memory: fast search, slow reopen, high memory usage"), DISK_WITH_CACHE("Code saved on disk with in memory cache: medium search, fast reopen, medium memory usage"), DISK("Everything on disk: slow search, fast reopen, low memory usage"); private final String desc; CodeCacheMode(String desc) { this.desc = desc; } public String getDesc() { return desc; } public static String buildToolTip() { return Stream.of(values()) .map(v -> v.name() + " - " + v.getDesc()) .collect(Collectors.joining("\n")); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/FixedCodeCache.java
jadx-gui/src/main/java/jadx/gui/cache/code/FixedCodeCache.java
package jadx.gui.cache.code; import jadx.api.ICodeCache; import jadx.api.ICodeInfo; import jadx.api.impl.DelegateCodeCache; /** * Code cache with fixed size of wrapped code cache ('remove' and 'add' methods will do nothing). */ public class FixedCodeCache extends DelegateCodeCache { public FixedCodeCache(ICodeCache codeCache) { super(codeCache); } @Override public void remove(String clsFullName) { // no op } @Override public void add(String clsFullName, ICodeInfo codeInfo) { // no op } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/disk/BufferCodeCache.java
jadx-gui/src/main/java/jadx/gui/cache/code/disk/BufferCodeCache.java
package jadx.gui.cache.code.disk; import java.io.IOException; import java.util.Deque; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import jadx.api.ICodeCache; import jadx.api.ICodeInfo; public class BufferCodeCache implements ICodeCache { private static final int BUFFER_SIZE = 20; private final ICodeCache backCache; private final Map<String, ICodeInfo> cache = new ConcurrentHashMap<>(); private final Deque<String> buffer = new ConcurrentLinkedDeque<>(); public BufferCodeCache(ICodeCache backCache) { this.backCache = backCache; } private void addInternal(String clsFullName, ICodeInfo codeInfo) { cache.put(clsFullName, codeInfo); buffer.addLast(clsFullName); if (buffer.size() > BUFFER_SIZE) { String removedKey = buffer.removeFirst(); cache.remove(removedKey); } } @Override public boolean contains(String clsFullName) { if (cache.containsKey(clsFullName)) { return true; } return backCache.contains(clsFullName); } @Override public void add(String clsFullName, ICodeInfo codeInfo) { addInternal(clsFullName, codeInfo); backCache.add(clsFullName, codeInfo); } @Override public @NotNull ICodeInfo get(String clsFullName) { ICodeInfo codeInfo = cache.get(clsFullName); if (codeInfo != null) { return codeInfo; } ICodeInfo backCodeInfo = backCache.get(clsFullName); if (backCodeInfo != ICodeInfo.EMPTY) { addInternal(clsFullName, backCodeInfo); } return backCodeInfo; } @Override public @Nullable String getCode(String clsFullName) { ICodeInfo codeInfo = cache.get(clsFullName); if (codeInfo != null) { return codeInfo.getCodeStr(); } return backCache.getCode(clsFullName); } @Override public void remove(String clsFullName) { cache.remove(clsFullName); backCache.remove(clsFullName); } @Override public void close() throws IOException { cache.clear(); buffer.clear(); backCache.close(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/disk/CodeMetadataAdapter.java
jadx-gui/src/main/java/jadx/gui/cache/code/disk/CodeMetadataAdapter.java
package jadx.gui.cache.code.disk; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.HashMap; import java.util.Map; import jadx.api.ICodeInfo; import jadx.api.impl.AnnotatedCodeInfo; import jadx.api.impl.SimpleCodeInfo; import jadx.api.metadata.ICodeAnnotation; import jadx.api.metadata.ICodeMetadata; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.files.FileUtils; import jadx.gui.cache.code.disk.adapters.CodeAnnotationAdapter; import jadx.gui.cache.code.disk.adapters.DataAdapterHelper; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import static java.nio.file.StandardOpenOption.WRITE; public class CodeMetadataAdapter { private static final byte[] JADX_METADATA_HEADER = "jadxmd".getBytes(StandardCharsets.US_ASCII); private final CodeAnnotationAdapter codeAnnotationAdapter; public CodeMetadataAdapter(RootNode root) { codeAnnotationAdapter = new CodeAnnotationAdapter(root); } public void write(Path metadataFile, ICodeMetadata metadata) { FileUtils.makeDirsForFile(metadataFile); try (OutputStream fileOutput = Files.newOutputStream(metadataFile, WRITE, CREATE, TRUNCATE_EXISTING); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(fileOutput))) { out.write(JADX_METADATA_HEADER); writeLines(out, metadata.getLineMapping()); writeAnnotations(out, metadata.getAsMap()); } catch (Exception e) { throw new RuntimeException("Failed to write metadata file", e); } } public ICodeInfo readAndBuild(Path metadataFile, String code) { if (!Files.exists(metadataFile)) { return new SimpleCodeInfo(code); } try (InputStream fileInput = Files.newInputStream(metadataFile); DataInputStream in = new DataInputStream(new BufferedInputStream(fileInput))) { in.skipBytes(JADX_METADATA_HEADER.length); Map<Integer, Integer> lines = readLines(in); Map<Integer, ICodeAnnotation> annotations = readAnnotations(in); return new AnnotatedCodeInfo(code, lines, annotations); } catch (Exception e) { throw new RuntimeException("Failed to parse code annotations", e); } } private void writeLines(DataOutput out, Map<Integer, Integer> lines) throws IOException { out.writeInt(lines.size()); for (Map.Entry<Integer, Integer> entry : lines.entrySet()) { DataAdapterHelper.writeUVInt(out, entry.getKey()); DataAdapterHelper.writeUVInt(out, entry.getValue()); } } private Map<Integer, Integer> readLines(DataInput in) throws IOException { int size = in.readInt(); if (size == 0) { return Collections.emptyMap(); } Map<Integer, Integer> lines = new HashMap<>(size); for (int i = 0; i < size; i++) { int key = DataAdapterHelper.readUVInt(in); int value = DataAdapterHelper.readUVInt(in); lines.put(key, value); } return lines; } private void writeAnnotations(DataOutputStream out, Map<Integer, ICodeAnnotation> annotations) throws IOException { out.writeInt(annotations.size()); for (Map.Entry<Integer, ICodeAnnotation> entry : annotations.entrySet()) { DataAdapterHelper.writeUVInt(out, entry.getKey()); codeAnnotationAdapter.write(out, entry.getValue()); } } private Map<Integer, ICodeAnnotation> readAnnotations(DataInputStream in) throws IOException { int size = in.readInt(); if (size == 0) { return Collections.emptyMap(); } Map<Integer, ICodeAnnotation> map = new HashMap<>(size); for (int i = 0; i < size; i++) { int pos = DataAdapterHelper.readUVInt(in); ICodeAnnotation ann = codeAnnotationAdapter.read(in); if (ann != null) { map.put(pos, ann); } } return map; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/disk/DiskCodeCache.java
jadx-gui/src/main/java/jadx/gui/cache/code/disk/DiskCodeCache.java
package jadx.gui.cache.code.disk; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeCache; import jadx.api.ICodeInfo; import jadx.api.JadxArgs; import jadx.api.JadxDecompiler; import jadx.core.Jadx; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.StringUtils; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.files.FileUtils; public class DiskCodeCache implements ICodeCache { private static final Logger LOG = LoggerFactory.getLogger(DiskCodeCache.class); private static final int DATA_FORMAT_VERSION = 15; private final Path baseDir; private final Path srcDir; private final Path metaDir; private final Path codeVersionFile; private final String codeVersion; private final CodeMetadataAdapter codeMetadataAdapter; private final ExecutorService writePool; private final Map<String, CacheData> clsDataMap; public DiskCodeCache(RootNode root, Path projectCacheDir) { baseDir = projectCacheDir.resolve("code"); srcDir = baseDir.resolve("sources"); metaDir = baseDir.resolve("metadata"); codeVersionFile = baseDir.resolve("code-version"); JadxArgs args = root.getArgs(); codeVersion = buildCodeVersion(args, root.getDecompiler()); writePool = Executors.newFixedThreadPool(args.getThreadsCount()); codeMetadataAdapter = new CodeMetadataAdapter(root); clsDataMap = buildClassDataMap(root.getClasses()); if (checkCodeVersion()) { loadCachedSet(); } else { reset(); } } private boolean checkCodeVersion() { try { if (!Files.exists(codeVersionFile)) { return false; } String currentCodeVer = FileUtils.readFile(codeVersionFile); return currentCodeVer.equals(codeVersion); } catch (Exception e) { LOG.warn("Failed to load code version file", e); return false; } } private void reset() { try { long start = System.currentTimeMillis(); LOG.info("Resetting disk code cache, base dir: {}", baseDir.toAbsolutePath()); FileUtils.deleteDirIfExists(baseDir); if (Files.exists(baseDir.getParent().resolve(codeVersionFile.getFileName()))) { // remove old version cache files FileUtils.deleteDirIfExists(baseDir.getParent()); } FileUtils.makeDirs(srcDir); FileUtils.makeDirs(metaDir); FileUtils.writeFile(codeVersionFile, codeVersion); if (LOG.isDebugEnabled()) { LOG.info("Reset done in: {}ms", System.currentTimeMillis() - start); } } catch (Exception e) { throw new JadxRuntimeException("Failed to reset code cache", e); } finally { clsDataMap.values().forEach(d -> d.setCached(false)); } } /** * Async writes backed by in-memory store */ @Override public void add(String clsFullName, ICodeInfo codeInfo) { CacheData clsData = getClsData(clsFullName); clsData.setTmpCodeInfo(codeInfo); clsData.setCached(true); writePool.execute(() -> { try { int clsId = clsData.getClsId(); ICodeInfo code = clsData.getTmpCodeInfo(); if (code != null) { FileUtils.writeFile(getJavaFile(clsId), code.getCodeStr()); codeMetadataAdapter.write(getMetadataFile(clsId), code.getCodeMetadata()); } } catch (Exception e) { LOG.error("Failed to write code cache for " + clsFullName, e); remove(clsFullName); } finally { clsData.setTmpCodeInfo(null); } }); } @Override public @Nullable String getCode(String clsFullName) { try { if (!contains(clsFullName)) { return null; } CacheData clsData = getClsData(clsFullName); ICodeInfo tmpCodeInfo = clsData.getTmpCodeInfo(); if (tmpCodeInfo != null) { return tmpCodeInfo.getCodeStr(); } Path javaFile = getJavaFile(clsData.getClsId()); if (!Files.exists(javaFile)) { return null; } return FileUtils.readFile(javaFile); } catch (Exception e) { LOG.error("Failed to read class code for {}", clsFullName, e); return null; } } @Override public @NotNull ICodeInfo get(String clsFullName) { try { if (!contains(clsFullName)) { return ICodeInfo.EMPTY; } CacheData clsData = getClsData(clsFullName); ICodeInfo tmpCodeInfo = clsData.getTmpCodeInfo(); if (tmpCodeInfo != null) { return tmpCodeInfo; } int clsId = clsData.getClsId(); Path javaFile = getJavaFile(clsId); if (!Files.exists(javaFile)) { return ICodeInfo.EMPTY; } String code = FileUtils.readFile(javaFile); return codeMetadataAdapter.readAndBuild(getMetadataFile(clsId), code); } catch (Exception e) { LOG.error("Failed to read code cache for {}", clsFullName, e); return ICodeInfo.EMPTY; } } @Override public boolean contains(String clsFullName) { return getClsData(clsFullName).isCached(); } @Override public void remove(String clsFullName) { try { CacheData clsData = getClsData(clsFullName); if (clsData.isCached()) { clsData.setCached(false); if (clsData.getTmpCodeInfo() == null) { LOG.debug("Removing class info from disk: {}", clsFullName); int clsId = clsData.getClsId(); Files.deleteIfExists(getJavaFile(clsId)); Files.deleteIfExists(getMetadataFile(clsId)); } else { // class info not yet written to disk clsData.setTmpCodeInfo(null); } } } catch (Exception e) { throw new JadxRuntimeException("Failed to remove code cache for " + clsFullName, e); } } private String buildCodeVersion(JadxArgs args, @Nullable JadxDecompiler decompiler) { List<File> inputFiles = new ArrayList<>(args.getInputFiles()); if (args.getGeneratedRenamesMappingFileMode().shouldRead() && args.getGeneratedRenamesMappingFile() != null && args.getGeneratedRenamesMappingFile().exists()) { inputFiles.add(args.getGeneratedRenamesMappingFile()); } return DATA_FORMAT_VERSION + ":" + Jadx.getVersion() + ":" + args.makeCodeArgsHash(decompiler) + ":" + FileUtils.buildInputsHash(Utils.collectionMap(inputFiles, File::toPath)); } private CacheData getClsData(String clsFullName) { CacheData clsData = clsDataMap.get(clsFullName); if (clsData == null) { throw new JadxRuntimeException("Unknown class name: " + clsFullName); } return clsData; } private void loadCachedSet() { long start = System.currentTimeMillis(); BitSet cachedSet = new BitSet(clsDataMap.size()); try (Stream<Path> stream = Files.walk(metaDir)) { stream.forEach(file -> { String fileName = file.getFileName().toString(); if (fileName.endsWith(".jadxmd")) { String idStr = StringUtils.removeSuffix(fileName, ".jadxmd"); int clsId = Integer.parseInt(idStr, 16); cachedSet.set(clsId); } }); } catch (Exception e) { throw new JadxRuntimeException("Failed to enumerate cached classes", e); } int count = 0; for (CacheData data : clsDataMap.values()) { int clsId = data.getClsId(); if (cachedSet.get(clsId)) { data.setCached(true); count++; } } LOG.info("Found {} classes in disk cache, time: {}ms, dir: {}", count, System.currentTimeMillis() - start, metaDir.getParent()); } private Path getJavaFile(int clsId) { return srcDir.resolve(getPathForClsId(clsId, ".java")); } private Path getMetadataFile(int clsId) { return metaDir.resolve(getPathForClsId(clsId, ".jadxmd")); } private Path getPathForClsId(int clsId, String ext) { // all classes divided between 256 top level folders String firstByte = FileUtils.byteToHex(clsId); return Paths.get(firstByte, FileUtils.intToHex(clsId) + ext); } private Map<String, CacheData> buildClassDataMap(List<ClassNode> classes) { int clsCount = classes.size(); Map<String, CacheData> map = new HashMap<>(clsCount); for (int i = 0; i < clsCount; i++) { ClassNode cls = classes.get(i); map.put(cls.getRawName(), new CacheData(i)); } return map; } @Override public void close() throws IOException { synchronized (this) { try { writePool.shutdown(); boolean completed = writePool.awaitTermination(1, TimeUnit.MINUTES); if (!completed) { LOG.warn("Disk code cache closing terminated by timeout"); } } catch (InterruptedException e) { LOG.error("Failed to close disk code cache", e); } } } private static final class CacheData { private final int clsId; private boolean cached; private @Nullable ICodeInfo tmpCodeInfo; public CacheData(int clsId) { this.clsId = clsId; } public int getClsId() { return clsId; } public boolean isCached() { return cached; } public void setCached(boolean cached) { this.cached = cached; } public @Nullable ICodeInfo getTmpCodeInfo() { return tmpCodeInfo; } public void setTmpCodeInfo(@Nullable ICodeInfo tmpCodeInfo) { this.tmpCodeInfo = tmpCodeInfo; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/ArgTypeAdapter.java
jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/ArgTypeAdapter.java
package jadx.gui.cache.code.disk.adapters; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import jadx.core.dex.instructions.args.ArgType; import jadx.core.utils.exceptions.JadxRuntimeException; public class ArgTypeAdapter implements DataAdapter<ArgType> { public static final ArgTypeAdapter INSTANCE = new ArgTypeAdapter(); private enum Types { NULL, UNKNOWN, PRIMITIVE, ARRAY, OBJECT, WILDCARD, GENERIC, TYPE_VARIABLE, OUTER_GENERIC } @Override public void write(DataOutput out, ArgType value) throws IOException { if (value == null) { writeType(out, Types.NULL); return; } if (!value.isTypeKnown()) { writeType(out, Types.UNKNOWN); return; } if (value.isPrimitive()) { writeType(out, Types.PRIMITIVE); out.writeByte(value.getPrimitiveType().getShortName().charAt(0)); return; } if (value.getOuterType() != null) { writeType(out, Types.OUTER_GENERIC); write(out, value.getOuterType()); write(out, value.getInnerType()); return; } if (value.getWildcardType() != null) { writeType(out, Types.WILDCARD); ArgType.WildcardBound bound = value.getWildcardBound(); out.writeByte(bound.getNum()); if (bound != ArgType.WildcardBound.UNBOUND) { write(out, value.getWildcardType()); } return; } if (value.isGeneric()) { writeType(out, Types.GENERIC); out.writeUTF(value.getObject()); writeTypesList(out, value.getGenericTypes()); return; } if (value.isGenericType()) { writeType(out, Types.TYPE_VARIABLE); out.writeUTF(value.getObject()); writeTypesList(out, value.getExtendTypes()); return; } if (value.isObject()) { writeType(out, Types.OBJECT); out.writeUTF(value.getObject()); return; } if (value.isArray()) { writeType(out, Types.ARRAY); out.writeByte(value.getArrayDimension()); write(out, value.getArrayRootElement()); return; } throw new JadxRuntimeException("Cannot save type: " + value + ", cls: " + value.getClass()); } private void writeType(DataOutput out, Types type) throws IOException { out.writeByte(type.ordinal()); } @Override public ArgType read(DataInput in) throws IOException { byte typeOrdinal = in.readByte(); Types type = Types.values()[typeOrdinal]; switch (type) { case NULL: return null; case UNKNOWN: return ArgType.UNKNOWN; case PRIMITIVE: char shortName = (char) in.readByte(); return ArgType.parse(shortName); case OUTER_GENERIC: ArgType outerType = read(in); ArgType innerType = read(in); return ArgType.outerGeneric(outerType, innerType); case WILDCARD: ArgType.WildcardBound bound = ArgType.WildcardBound.getByNum(in.readByte()); if (bound == ArgType.WildcardBound.UNBOUND) { return ArgType.WILDCARD; } ArgType objType = read(in); return ArgType.wildcard(objType, bound); case GENERIC: String clsType = in.readUTF(); return ArgType.generic(clsType, readTypesList(in)); case TYPE_VARIABLE: String typeVar = in.readUTF(); List<ArgType> extendTypes = readTypesList(in); return ArgType.genericType(typeVar, extendTypes); case OBJECT: return ArgType.object(in.readUTF()); case ARRAY: int dim = in.readByte(); ArgType rootType = read(in); return ArgType.array(rootType, dim); default: throw new RuntimeException("Unexpected arg type: " + type); } } private void writeTypesList(DataOutput out, List<ArgType> types) throws IOException { out.writeByte(types.size()); for (ArgType type : types) { write(out, type); } } private List<ArgType> readTypesList(DataInput in) throws IOException { byte size = in.readByte(); if (size == 0) { return Collections.emptyList(); } List<ArgType> list = new ArrayList<>(size); for (int i = 0; i < size; i++) { list.add(read(in)); } return list; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/MethodNodeAdapter.java
jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/MethodNodeAdapter.java
package jadx.gui.cache.code.disk.adapters; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; public class MethodNodeAdapter implements DataAdapter<MethodNode> { private final RootNode root; public MethodNodeAdapter(RootNode root) { this.root = root; } @Override public void write(DataOutput out, MethodNode value) throws IOException { MethodInfo methodInfo = value.getMethodInfo(); out.writeUTF(methodInfo.getDeclClass().getRawName()); out.writeUTF(methodInfo.getShortId()); } @Override public MethodNode read(DataInput in) throws IOException { String cls = in.readUTF(); String sign = in.readUTF(); return root.resolveDirectMethod(cls, sign); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/NodeDeclareRefAdapter.java
jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/NodeDeclareRefAdapter.java
package jadx.gui.cache.code.disk.adapters; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import jadx.api.metadata.ICodeNodeRef; import jadx.api.metadata.annotations.NodeDeclareRef; public class NodeDeclareRefAdapter implements DataAdapter<NodeDeclareRef> { private final CodeAnnotationAdapter refAdapter; public NodeDeclareRefAdapter(CodeAnnotationAdapter refAdapter) { this.refAdapter = refAdapter; } @Override public void write(DataOutput out, NodeDeclareRef value) throws IOException { ICodeNodeRef node = value.getNode(); if (node == null) { throw new RuntimeException("Null node in NodeDeclareRef"); } refAdapter.write(out, node); DataAdapterHelper.writeUVInt(out, value.getDefPos()); } @Override public NodeDeclareRef read(DataInput in) throws IOException { ICodeNodeRef ref = (ICodeNodeRef) refAdapter.read(in); int defPos = DataAdapterHelper.readUVInt(in); NodeDeclareRef nodeDeclareRef = new NodeDeclareRef(ref); nodeDeclareRef.setDefPos(defPos); // restore def position if loading metadata without actual decompilation ref.setDefPosition(defPos); return nodeDeclareRef; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/NodeEndAdapter.java
jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/NodeEndAdapter.java
package jadx.gui.cache.code.disk.adapters; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import jadx.api.metadata.annotations.NodeEnd; public class NodeEndAdapter implements DataAdapter<NodeEnd> { @Override public void write(DataOutput out, NodeEnd value) throws IOException { } @Override public NodeEnd read(DataInput in) throws IOException { return NodeEnd.VALUE; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/InsnCodeOffsetAdapter.java
jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/InsnCodeOffsetAdapter.java
package jadx.gui.cache.code.disk.adapters; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import jadx.api.metadata.annotations.InsnCodeOffset; public class InsnCodeOffsetAdapter implements DataAdapter<InsnCodeOffset> { public static final InsnCodeOffsetAdapter INSTANCE = new InsnCodeOffsetAdapter(); @Override public void write(DataOutput out, InsnCodeOffset value) throws IOException { DataAdapterHelper.writeUVInt(out, value.getOffset()); } @Override public InsnCodeOffset read(DataInput in) throws IOException { return new InsnCodeOffset(DataAdapterHelper.readUVInt(in)); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/CodeAnnotationAdapter.java
jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/CodeAnnotationAdapter.java
package jadx.gui.cache.code.disk.adapters; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.EnumMap; import java.util.Map; import jadx.api.metadata.ICodeAnnotation; import jadx.api.metadata.ICodeAnnotation.AnnType; import jadx.core.dex.nodes.RootNode; public class CodeAnnotationAdapter implements DataAdapter<ICodeAnnotation> { private final Map<AnnType, TypeInfo> adaptersByCls; private final TypeInfo[] adaptersByTag; public CodeAnnotationAdapter(RootNode root) { Map<AnnType, DataAdapter<?>> map = registerAdapters(root); int size = map.size(); adaptersByCls = new EnumMap<>(AnnType.class); adaptersByTag = new TypeInfo[size + 1]; int tag = 1; for (Map.Entry<AnnType, DataAdapter<?>> entry : map.entrySet()) { TypeInfo typeInfo = new TypeInfo(tag, entry.getValue()); adaptersByCls.put(entry.getKey(), typeInfo); adaptersByTag[tag] = typeInfo; tag++; } } private Map<AnnType, DataAdapter<?>> registerAdapters(RootNode root) { Map<AnnType, DataAdapter<?>> map = new EnumMap<>(AnnType.class); MethodNodeAdapter mthAdapter = new MethodNodeAdapter(root); map.put(AnnType.CLASS, new ClassNodeAdapter(root)); map.put(AnnType.FIELD, new FieldNodeAdapter(root)); map.put(AnnType.METHOD, mthAdapter); map.put(AnnType.DECLARATION, new NodeDeclareRefAdapter(this)); map.put(AnnType.VAR, new VarNodeAdapter(mthAdapter)); map.put(AnnType.VAR_REF, VarRefAdapter.INSTANCE); map.put(AnnType.OFFSET, InsnCodeOffsetAdapter.INSTANCE); map.put(AnnType.END, new NodeEndAdapter()); return map; } @SuppressWarnings("unchecked") @Override public void write(DataOutput out, ICodeAnnotation value) throws IOException { if (value == null) { out.writeByte(0); return; } TypeInfo typeInfo = adaptersByCls.get(value.getAnnType()); if (typeInfo == null) { throw new RuntimeException("Unexpected code annotation type: " + value.getClass().getSimpleName()); } out.writeByte(typeInfo.getTag()); typeInfo.getAdapter().write(out, value); } @Override public ICodeAnnotation read(DataInput in) throws IOException { int tag = in.readByte(); if (tag == 0) { return null; } TypeInfo typeInfo = adaptersByTag[tag]; if (typeInfo == null) { throw new RuntimeException("Unknown type tag: " + tag); } return (ICodeAnnotation) typeInfo.getAdapter().read(in); } @SuppressWarnings("rawtypes") private static class TypeInfo { private final int tag; private final DataAdapter adapter; private TypeInfo(int tag, DataAdapter adapter) { this.tag = tag; this.adapter = adapter; } public int getTag() { return tag; } public DataAdapter getAdapter() { return adapter; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/VarNodeAdapter.java
jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/VarNodeAdapter.java
package jadx.gui.cache.code.disk.adapters; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import jadx.api.metadata.annotations.VarNode; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.MethodNode; import static jadx.gui.cache.code.disk.adapters.DataAdapterHelper.readNullableUTF; import static jadx.gui.cache.code.disk.adapters.DataAdapterHelper.readUVInt; import static jadx.gui.cache.code.disk.adapters.DataAdapterHelper.writeNullableUTF; import static jadx.gui.cache.code.disk.adapters.DataAdapterHelper.writeUVInt; public class VarNodeAdapter implements DataAdapter<VarNode> { private final MethodNodeAdapter mthAdapter; public VarNodeAdapter(MethodNodeAdapter mthAdapter) { this.mthAdapter = mthAdapter; } @Override public void write(DataOutput out, VarNode value) throws IOException { mthAdapter.write(out, value.getMth()); writeUVInt(out, value.getReg()); writeUVInt(out, value.getSsa()); ArgTypeAdapter.INSTANCE.write(out, value.getType()); writeNullableUTF(out, value.getName()); } @Override public VarNode read(DataInput in) throws IOException { MethodNode mth = mthAdapter.read(in); int reg = readUVInt(in); int ssa = readUVInt(in); ArgType type = ArgTypeAdapter.INSTANCE.read(in); String name = readNullableUTF(in); return new VarNode(mth, reg, ssa, type, name); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/VarRefAdapter.java
jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/VarRefAdapter.java
package jadx.gui.cache.code.disk.adapters; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import jadx.api.metadata.annotations.VarRef; public class VarRefAdapter implements DataAdapter<VarRef> { public static final VarRefAdapter INSTANCE = new VarRefAdapter(); @Override public void write(DataOutput out, VarRef value) throws IOException { int refPos = value.getRefPos(); DataAdapterHelper.writeUVInt(out, refPos); } @Override public VarRef read(DataInput in) throws IOException { int refPos = DataAdapterHelper.readUVInt(in); return VarRef.fromPos(refPos); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/DataAdapterHelper.java
jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/DataAdapterHelper.java
package jadx.gui.cache.code.disk.adapters; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.jetbrains.annotations.Nullable; public class DataAdapterHelper { public static void writeNullableUTF(DataOutput out, @Nullable String str) throws IOException { if (str == null) { out.writeByte(0); } else { out.writeByte(1); out.writeUTF(str); } } public static @Nullable String readNullableUTF(DataInput in) throws IOException { if (in.readByte() == 0) { return null; } return in.readUTF(); } /** * Write unsigned variable length integer (ULEB128 encoding) */ public static void writeUVInt(DataOutput out, int val) throws IOException { if (val < 0) { throw new IllegalArgumentException("Expect value >= 0, got: " + val); } int current = val; int next = val; while (true) { next >>>= 7; if (next == 0) { // last byte out.writeByte(current & 0x7f); return; } out.writeByte((current & 0x7f) | 0x80); current = next; } } /** * Read unsigned variable length integer (ULEB128 encoding) */ public static int readUVInt(DataInput in) throws IOException { int result = 0; int shift = 0; while (true) { byte v = in.readByte(); result |= (v & (byte) 0x7f) << shift; shift += 7; if ((v & 0x80) != 0x80) { return result; } } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/FieldNodeAdapter.java
jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/FieldNodeAdapter.java
package jadx.gui.cache.code.disk.adapters; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import jadx.core.dex.info.FieldInfo; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.RootNode; public class FieldNodeAdapter implements DataAdapter<FieldNode> { private final RootNode root; public FieldNodeAdapter(RootNode root) { this.root = root; } @Override public void write(DataOutput out, FieldNode value) throws IOException { FieldInfo fieldInfo = value.getFieldInfo(); out.writeUTF(fieldInfo.getDeclClass().getRawName()); out.writeUTF(fieldInfo.getShortId()); } @Override public FieldNode read(DataInput in) throws IOException { String cls = in.readUTF(); String sign = in.readUTF(); ClassNode clsNode = root.resolveRawClass(cls); if (clsNode == null) { throw new RuntimeException("Class not found: " + cls); } FieldNode fieldNode = clsNode.searchFieldByShortId(sign); if (fieldNode == null) { throw new RuntimeException("Field not found: " + cls + "." + sign); } return fieldNode; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/ClassNodeAdapter.java
jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/ClassNodeAdapter.java
package jadx.gui.cache.code.disk.adapters; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.RootNode; public class ClassNodeAdapter implements DataAdapter<ClassNode> { private final RootNode root; public ClassNodeAdapter(RootNode root) { this.root = root; } @Override public void write(DataOutput out, ClassNode value) throws IOException { out.writeUTF(value.getClassInfo().getRawName()); } @Override public ClassNode read(DataInput in) throws IOException { return root.resolveRawClass(in.readUTF()); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/DataAdapter.java
jadx-gui/src/main/java/jadx/gui/cache/code/disk/adapters/DataAdapter.java
package jadx.gui.cache.code.disk.adapters; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; public interface DataAdapter<T> { void write(DataOutput out, T value) throws IOException; T read(DataInput in) throws IOException; }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/manager/CacheManager.java
jadx-gui/src/main/java/jadx/gui/cache/manager/CacheManager.java
package jadx.gui.cache.manager; import java.io.BufferedReader; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; 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 java.util.Objects; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import jadx.api.plugins.utils.CommonFileUtils; import jadx.core.utils.GsonUtils; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.files.FileUtils; import jadx.gui.settings.JadxProject; import jadx.gui.settings.JadxSettings; import jadx.gui.settings.data.ProjectData; import jadx.gui.utils.files.JadxFiles; public class CacheManager { private static final Logger LOG = LoggerFactory.getLogger(CacheManager.class); private static final Gson GSON = GsonUtils.buildGson(); private static final Type CACHES_TYPE = new TypeToken<List<CacheEntry>>() { }.getType(); private final Map<String, CacheEntry> cacheMap; private final JadxSettings settings; public CacheManager(JadxSettings settings) { this.settings = settings; this.cacheMap = loadCaches(); } /** * If project cache is set -&gt; check if cache entry exists for this project. * If not -&gt; calculate new and add entry. */ public Path getCacheDir(JadxProject project, @Nullable String cacheDirStr) { if (cacheDirStr == null) { Path newProjectCacheDir = buildCacheDir(project); addEntry(projectToKey(project), newProjectCacheDir); return newProjectCacheDir; } Path cacheDir = resolveCacheDirStr(cacheDirStr, project.getProjectPath()); return verifyEntry(project, cacheDir); } public void projectPathUpdate(JadxProject project, Path newPath) { if (Objects.equals(project.getProjectPath(), newPath)) { return; } String key = projectToKey(project); CacheEntry prevEntry = cacheMap.remove(key); if (prevEntry == null) { return; } CacheEntry newEntry = new CacheEntry(); newEntry.setProject(pathToString(newPath)); newEntry.setCache(prevEntry.getCache()); addEntry(newEntry); } public List<CacheEntry> getCachesList() { List<CacheEntry> list = new ArrayList<>(cacheMap.values()); Collections.sort(list); return list; } public synchronized void removeCacheEntry(CacheEntry entry) { try { cacheMap.remove(entry.getProject()); saveCaches(cacheMap); FileUtils.deleteDirIfExists(Paths.get(entry.getCache())); } catch (Exception e) { LOG.error("Failed to remove cache entry: " + entry.getCache(), e); } } private Path resolveCacheDirStr(String cacheDirStr, Path projectPath) { Path path = Paths.get(cacheDirStr); if (path.isAbsolute() || projectPath == null) { return path; } return projectPath.resolveSibling(path); } public String buildCacheDirStr(Path dir) { if (Objects.equals(settings.getCacheDir(), ".")) { return dir.getFileName().toString(); } return pathToString(dir); } private Path buildCacheDir(JadxProject project) { String cacheDirValue = settings.getCacheDir(); if (Objects.equals(cacheDirValue, ".")) { return buildLocalCacheDir(project); } Path cacheBaseDir = cacheDirValue == null ? JadxFiles.PROJECTS_CACHE_DIR : Paths.get(cacheDirValue); return cacheBaseDir.resolve(buildProjectUniqName(project)); } private static Path buildLocalCacheDir(JadxProject project) { Path projectPath = project.getProjectPath(); if (projectPath != null) { return projectPath.resolveSibling(projectPath.getFileName() + ".cache"); } List<Path> files = project.getFilePaths(); if (files.isEmpty()) { throw new JadxRuntimeException("Failed to build local cache dir"); } Path path = files.stream() .filter(p -> !p.getFileName().toString().endsWith(".jadx.kts")) .findFirst() .orElseGet(() -> files.get(0)); String name = CommonFileUtils.removeFileExtension(path.getFileName().toString()); return path.resolveSibling(name + ".jadx.cache"); } private Path verifyEntry(JadxProject project, Path cacheDir) { boolean cacheExists = Files.exists(cacheDir); String key = projectToKey(project); CacheEntry entry = cacheMap.get(key); if (entry == null) { Path newCacheDir = cacheExists ? cacheDir : buildCacheDir(project); addEntry(key, newCacheDir); return newCacheDir; } if (entry.getCache().equals(pathToString(cacheDir)) && cacheExists) { // same and exists return cacheDir; } // remove previous cache dir FileUtils.deleteDirIfExists(Paths.get(entry.getCache())); Path newCacheDir = cacheExists ? cacheDir : buildCacheDir(project); entry.setCache(pathToString(newCacheDir)); entry.setTimestamp(System.currentTimeMillis()); saveCaches(cacheMap); return newCacheDir; } private void addEntry(String projectKey, Path cacheDir) { CacheEntry entry = new CacheEntry(); entry.setProject(projectKey); entry.setCache(pathToString(cacheDir)); addEntry(entry); } private void addEntry(CacheEntry entry) { entry.setTimestamp(System.currentTimeMillis()); cacheMap.put(entry.getProject(), entry); saveCaches(cacheMap); } private String projectToKey(JadxProject project) { Path projectPath = project.getProjectPath(); if (projectPath != null) { return pathToString(projectPath); } return "tmp:" + buildProjectUniqName(project); } private static String buildProjectUniqName(JadxProject project) { return project.getName() + "-" + FileUtils.buildInputsHash(project.getFilePaths()); } public static String pathToString(Path path) { try { return path.toAbsolutePath().normalize().toString(); } catch (Exception e) { throw new JadxRuntimeException("Failed to expand path: " + path, e); } } private synchronized Map<String, CacheEntry> loadCaches() { List<CacheEntry> list = null; if (Files.exists(JadxFiles.CACHES_LIST)) { try (BufferedReader reader = Files.newBufferedReader(JadxFiles.CACHES_LIST)) { list = GSON.fromJson(reader, CACHES_TYPE); } catch (Exception e) { LOG.warn("Failed to load caches list", e); } } else { return initFromRecentProjects(); } if (Utils.isEmpty(list)) { return new HashMap<>(); } Map<String, CacheEntry> map = new HashMap<>(list.size()); for (CacheEntry entry : list) { map.put(entry.getProject(), entry); } return map; } private synchronized void saveCaches(Map<String, CacheEntry> map) { List<CacheEntry> list = new ArrayList<>(map.values()); Collections.sort(list); String json = GSON.toJson(list, CACHES_TYPE); try { Files.writeString(JadxFiles.CACHES_LIST, json, StandardCharsets.UTF_8, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (Exception e) { throw new JadxRuntimeException("Failed to write caches file", e); } } /** * Load caches info from recent projects list. * Help for initial migration. */ private Map<String, CacheEntry> initFromRecentProjects() { try { Map<String, CacheEntry> map = new HashMap<>(); long t = System.currentTimeMillis(); for (Path project : settings.getRecentProjects()) { try { ProjectData data = JadxProject.loadProjectData(project); String cacheDir = data.getCacheDir(); if (cacheDir == null) { // no cache dir, ignore continue; } Path cachePath = resolveCacheDirStr(cacheDir, project); if (!Files.isDirectory(cachePath)) { continue; } String key = pathToString(project); CacheEntry entry = new CacheEntry(); entry.setProject(key); entry.setCache(pathToString(cachePath)); entry.setTimestamp(t++); // keep projects order map.put(key, entry); } catch (Exception e) { LOG.warn("Failed to load project file: {}", project, e); } } saveCaches(map); return map; } catch (Exception e) { LOG.warn("Failed to fill cache list from recent projects", e); return new HashMap<>(); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/manager/CacheEntry.java
jadx-gui/src/main/java/jadx/gui/cache/manager/CacheEntry.java
package jadx.gui.cache.manager; import org.jetbrains.annotations.NotNull; public class CacheEntry implements Comparable<CacheEntry> { private String project; private String cache; private long timestamp; public String getProject() { return project; } public void setProject(String project) { this.project = project; } public String getCache() { return cache; } public void setCache(String cache) { this.cache = cache; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } @Override public int compareTo(@NotNull CacheEntry other) { // recent entries first return -Long.compare(timestamp, other.timestamp); } @Override public String toString() { return "CacheEntry{project=" + project + ", cache=" + cache + "}"; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/usage/FldRef.java
jadx-gui/src/main/java/jadx/gui/cache/usage/FldRef.java
package jadx.gui.cache.usage; final class FldRef { private final String cls; private final String shortId; FldRef(String cls, String shortId) { this.cls = cls; this.shortId = shortId; } public String getCls() { return cls; } public String getShortId() { return shortId; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/usage/UsageInfoCache.java
jadx-gui/src/main/java/jadx/gui/cache/usage/UsageInfoCache.java
package jadx.gui.cache.usage; import java.io.File; import java.nio.file.Path; import java.util.List; import org.jetbrains.annotations.Nullable; import jadx.api.usage.IUsageInfoCache; import jadx.api.usage.IUsageInfoData; import jadx.api.usage.impl.InMemoryUsageInfoCache; import jadx.core.dex.nodes.RootNode; public class UsageInfoCache implements IUsageInfoCache { private static final Object LOAD_DATA_SYNC = new Object(); private final Path usageFile; private final List<File> inputs; private final InMemoryUsageInfoCache memCache = new InMemoryUsageInfoCache(); private @Nullable RawUsageData rawUsageData; public UsageInfoCache(Path cacheDir, List<File> inputFiles) { usageFile = cacheDir.resolve("usage"); inputs = inputFiles; } @Override public @Nullable IUsageInfoData get(RootNode root) { IUsageInfoData memData = memCache.get(root); if (memData != null) { return memData; } synchronized (LOAD_DATA_SYNC) { if (rawUsageData == null) { rawUsageData = UsageFileAdapter.load(usageFile, inputs); } if (rawUsageData != null) { UsageData data = new UsageData(root, rawUsageData); memCache.set(root, data); return data; } } return null; } @Override public void set(RootNode root, IUsageInfoData data) { memCache.set(root, data); UsageFileAdapter.save(data, usageFile, inputs); } @Override public void close() { rawUsageData = null; memCache.close(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/usage/UsageFileAdapter.java
jadx-gui/src/main/java/jadx/gui/cache/usage/UsageFileAdapter.java
package jadx.gui.cache.usage; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; 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.stream.Collectors; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.usage.IUsageInfoData; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.files.FileUtils; import jadx.gui.cache.code.disk.adapters.DataAdapterHelper; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import static java.nio.file.StandardOpenOption.WRITE; public class UsageFileAdapter extends DataAdapterHelper { private static final Logger LOG = LoggerFactory.getLogger(UsageFileAdapter.class); private static final int USAGE_DATA_VERSION = 1; private static final byte[] JADX_USAGE_HEADER = "jadx.usage".getBytes(StandardCharsets.US_ASCII); public static synchronized @Nullable RawUsageData load(Path usageFile, List<File> inputs) { if (!Files.isRegularFile(usageFile)) { return null; } long start = System.currentTimeMillis(); try (DataInputStream in = new DataInputStream(new BufferedInputStream(Files.newInputStream(usageFile)))) { in.skipBytes(JADX_USAGE_HEADER.length); int dataVersion = in.readInt(); if (dataVersion != USAGE_DATA_VERSION) { LOG.debug("Found old usage data format"); FileUtils.deleteFileIfExists(usageFile); return null; } String inputsHash = buildInputsHash(inputs); String fileInputsHash = in.readUTF(); if (!inputsHash.equals(fileInputsHash)) { LOG.debug("Found usage data with different inputs hash"); FileUtils.deleteFileIfExists(usageFile); return null; } RawUsageData data = readData(in); if (LOG.isDebugEnabled()) { LOG.debug("Loaded usage data from disk cache, classes count: {}, time: {}ms, file: {}", data.getClsMap().size(), System.currentTimeMillis() - start, usageFile); } return data; } catch (Exception e) { try { FileUtils.deleteFileIfExists(usageFile); } catch (IOException ex) { // ignore } LOG.error("Failed to load usage data file", e); return null; } } public static synchronized void save(IUsageInfoData data, Path usageFile, List<File> inputs) { long start = System.currentTimeMillis(); FileUtils.makeDirsForFile(usageFile); String inputsHash = buildInputsHash(inputs); RawUsageData usageData = new RawUsageData(); data.visitUsageData(new CollectUsageData(usageData)); try (OutputStream fileOutput = Files.newOutputStream(usageFile, WRITE, CREATE, TRUNCATE_EXISTING); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(fileOutput))) { out.write(JADX_USAGE_HEADER); out.writeInt(USAGE_DATA_VERSION); out.writeUTF(inputsHash); writeData(out, usageData); } catch (Exception e) { LOG.error("Failed to save usage data file", e); try { FileUtils.deleteFileIfExists(usageFile); } catch (IOException ex) { LOG.error("Failed to delete usage data file: {}", usageFile, ex); } } if (LOG.isDebugEnabled()) { LOG.debug("Usage data saved, time: {}ms, file: {}", System.currentTimeMillis() - start, usageFile); } } private static RawUsageData readData(DataInputStream in) throws IOException { RawUsageData data = new RawUsageData(); int clsCount = readUVInt(in); int clsWithoutDataCount = readUVInt(in); String[] clsNames = new String[clsCount + clsWithoutDataCount]; ClsUsageData[] classes = new ClsUsageData[clsCount]; int c = 0; for (int i = 0; i < clsCount; i++) { String clsRawName = in.readUTF(); classes[i] = data.getClassData(clsRawName); clsNames[c++] = clsRawName; } for (int i = 0; i < clsWithoutDataCount; i++) { clsNames[c++] = in.readUTF(); } int mthCount = readUVInt(in); MthRef[] methods = new MthRef[mthCount]; for (int i = 0; i < mthCount; i++) { int clsId = readUVInt(in); String mthShortId = in.readUTF(); ClsUsageData cls = classes[clsId]; MthRef mthRef = new MthRef(cls.getRawName(), mthShortId); cls.getMthUsage().put(mthShortId, new MthUsageData(mthRef)); methods[i] = mthRef; } for (int i = 0; i < clsCount; i++) { ClsUsageData cls = data.getClassData(clsNames[i]); cls.setClsDeps(readClsList(in, clsNames)); cls.setClsUsage(readClsList(in, clsNames)); cls.setClsUseInMth(readMthList(in, methods)); int mCount = readUVInt(in); for (int m = 0; m < mCount; m++) { MthRef mthRef = methods[readUVInt(in)]; cls.getMthUsage().get(mthRef.getShortId()) .setUsage(readMthList(in, methods)); } int fCount = readUVInt(in); for (int f = 0; f < fCount; f++) { String fldShortId = in.readUTF(); cls.getFldUsage().computeIfAbsent(fldShortId, fldId -> new FldUsageData(new FldRef(cls.getRawName(), fldId))) .setUsage(readMthList(in, methods)); } } return data; } private static void writeData(DataOutputStream out, RawUsageData usageData) throws IOException { Map<String, Integer> clsMap = new HashMap<>(); Map<MthRef, Integer> mthMap = new HashMap<>(); Map<String, ClsUsageData> clsDataMap = usageData.getClsMap(); List<String> classes = new ArrayList<>(clsDataMap.keySet()); Collections.sort(classes); List<String> classesWithoutData = usageData.getClassesWithoutData(); writeUVInt(out, classes.size()); writeUVInt(out, classesWithoutData.size()); int i = 0; for (String cls : classes) { out.writeUTF(cls); clsMap.put(cls, i++); } for (String cls : classesWithoutData) { out.writeUTF(cls); clsMap.put(cls, i++); } List<MthRef> methods = clsDataMap.values().stream() .flatMap(c -> c.getMthUsage().values().stream()) .map(MthUsageData::getMthRef) .collect(Collectors.toList()); writeUVInt(out, methods.size()); int j = 0; for (MthRef mth : methods) { writeUVInt(out, clsMap.get(mth.getCls())); out.writeUTF(mth.getShortId()); mthMap.put(mth, j++); } for (String cls : classes) { ClsUsageData clsData = clsDataMap.get(cls); writeClsList(out, clsMap, clsData.getClsDeps()); writeClsList(out, clsMap, clsData.getClsUsage()); writeMthList(out, mthMap, clsData.getClsUseInMth()); writeUVInt(out, clsData.getMthUsage().size()); for (MthUsageData mthData : clsData.getMthUsage().values()) { writeUVInt(out, mthMap.get(mthData.getMthRef())); writeMthList(out, mthMap, mthData.getUsage()); } writeUVInt(out, clsData.getFldUsage().size()); for (FldUsageData fldData : clsData.getFldUsage().values()) { out.writeUTF(fldData.getFldRef().getShortId()); writeMthList(out, mthMap, fldData.getUsage()); } } } private static List<String> readClsList(DataInputStream in, String[] classes) throws IOException { int count = readUVInt(in); if (count == 0) { return Collections.emptyList(); } List<String> list = new ArrayList<>(count); for (int i = 0; i < count; i++) { list.add(classes[readUVInt(in)]); } return list; } private static void writeClsList(DataOutputStream out, Map<String, Integer> clsMap, List<String> clsList) throws IOException { if (Utils.isEmpty(clsList)) { writeUVInt(out, 0); return; } writeUVInt(out, clsList.size()); for (String cls : clsList) { Integer clsId = clsMap.get(cls); if (clsId == null) { throw new JadxRuntimeException("Unknown class in usage: " + cls); } writeUVInt(out, clsId); } } private static List<MthRef> readMthList(DataInputStream in, MthRef[] methods) throws IOException { int count = readUVInt(in); if (count == 0) { return Collections.emptyList(); } List<MthRef> list = new ArrayList<>(count); for (int i = 0; i < count; i++) { list.add(methods[readUVInt(in)]); } return list; } private static void writeMthList(DataOutputStream out, Map<MthRef, Integer> mthMap, List<MthRef> mthList) throws IOException { if (Utils.isEmpty(mthList)) { writeUVInt(out, 0); return; } writeUVInt(out, mthList.size()); for (MthRef mth : mthList) { writeUVInt(out, mthMap.get(mth)); } } private static String buildInputsHash(List<File> inputs) { List<Path> paths = inputs.stream() .filter(f -> !f.getName().endsWith(".jadx.kts")) .map(File::toPath) .collect(Collectors.toList()); return FileUtils.buildInputsHash(paths); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/usage/RawUsageData.java
jadx-gui/src/main/java/jadx/gui/cache/usage/RawUsageData.java
package jadx.gui.cache.usage; 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 jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.MethodNode; class RawUsageData { private final Map<String, ClsUsageData> clsMap = new HashMap<>(); private List<String> classesWithoutData = Collections.emptyList(); public Map<String, ClsUsageData> getClsMap() { return clsMap; } public List<String> getClassesWithoutData() { return classesWithoutData; } public ClsUsageData getClassData(ClassNode cls) { return getClassData(cls.getRawName()); } public ClsUsageData getClassData(String clsRawName) { return clsMap.computeIfAbsent(clsRawName, ClsUsageData::new); } public MthUsageData getMethodData(MethodNode mth) { ClassNode parentClass = mth.getParentClass(); String shortId = mth.getMethodInfo().getShortId(); return getClassData(parentClass).getMthUsage().computeIfAbsent(shortId, m -> new MthUsageData(new MthRef(parentClass.getRawName(), shortId))); } public FldUsageData getFieldData(FieldNode fld) { ClassNode parentClass = fld.getParentClass(); String shortId = fld.getFieldInfo().getShortId(); return getClassData(parentClass).getFldUsage().computeIfAbsent(shortId, m -> new FldUsageData(new FldRef(parentClass.getRawName(), shortId))); } public void collectClassesWithoutData() { Set<String> allClasses = new HashSet<>(clsMap.size() * 2); for (ClsUsageData usageData : clsMap.values()) { List<String> deps = usageData.getClsDeps(); if (deps != null) { allClasses.addAll(deps); } List<String> usage = usageData.getClsUsage(); if (usage != null) { allClasses.addAll(usage); } } allClasses.removeAll(clsMap.keySet()); classesWithoutData = new ArrayList<>(allClasses); Collections.sort(classesWithoutData); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/usage/UsageData.java
jadx-gui/src/main/java/jadx/gui/cache/usage/UsageData.java
package jadx.gui.cache.usage; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.usage.IUsageInfoData; import jadx.api.usage.IUsageInfoVisitor; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.nodes.RootNode; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; class UsageData implements IUsageInfoData { private static final Logger LOG = LoggerFactory.getLogger(UsageData.class); private final RootNode root; private final RawUsageData rawUsageData; public UsageData(RootNode root, RawUsageData rawUsageData) { this.root = root; this.rawUsageData = rawUsageData; } @Override public void apply() { Map<String, ClsUsageData> clsMap = rawUsageData.getClsMap(); for (ClassNode cls : root.getClasses()) { String clsRawName = cls.getRawName(); ClsUsageData clsUsageData = clsMap.get(clsRawName); if (clsUsageData != null) { applyForClass(clsUsageData, cls); } } } @Override public void applyForClass(ClassNode cls) { String clsRawName = cls.getRawName(); ClsUsageData clsUsageData = rawUsageData.getClsMap().get(clsRawName); if (clsUsageData == null) { LOG.debug("No usage data for class: {}", clsRawName); return; } applyForClass(clsUsageData, cls); } private void applyForClass(ClsUsageData clsUsageData, ClassNode cls) { cls.setDependencies(resolveClsList(clsUsageData.getClsDeps())); cls.setUseIn(resolveClsList(clsUsageData.getClsUsage())); cls.setUseInMth(resolveMthList(clsUsageData.getClsUseInMth())); Map<String, MthUsageData> mthUsage = clsUsageData.getMthUsage(); for (MethodNode mth : cls.getMethods()) { MthUsageData mthUsageData = mthUsage.get(mth.getMethodInfo().getShortId()); if (mthUsageData != null) { mth.setUseIn(resolveMthList(mthUsageData.getUsage())); } } Map<String, FldUsageData> fldUsage = clsUsageData.getFldUsage(); for (FieldNode fld : cls.getFields()) { FldUsageData fldUsageData = fldUsage.get(fld.getFieldInfo().getShortId()); if (fldUsageData != null) { fld.setUseIn(resolveMthList(fldUsageData.getUsage())); } } } @Override public void visitUsageData(IUsageInfoVisitor visitor) { throw new JadxRuntimeException("Not implemented"); } private List<ClassNode> resolveClsList(List<String> clsList) { return Utils.collectionMap(clsList, root::resolveRawClass); } private List<MethodNode> resolveMthList(List<MthRef> mthRefList) { return Utils.collectionMap(mthRefList, m -> root.resolveDirectMethod(m.getCls(), m.getShortId())); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/usage/CollectUsageData.java
jadx-gui/src/main/java/jadx/gui/cache/usage/CollectUsageData.java
package jadx.gui.cache.usage; import java.util.List; import jadx.api.usage.IUsageInfoVisitor; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.utils.Utils; final class CollectUsageData implements IUsageInfoVisitor { private final RawUsageData data; public CollectUsageData(RawUsageData usageData) { data = usageData; } @Override public void visitClassDeps(ClassNode cls, List<ClassNode> deps) { data.getClassData(cls).setClsDeps(clsNodesRef(deps)); } @Override public void visitClassUsage(ClassNode cls, List<ClassNode> usage) { data.getClassData(cls).setClsUsage(clsNodesRef(usage)); } @Override public void visitClassUseInMethods(ClassNode cls, List<MethodNode> methods) { data.getClassData(cls).setClsUseInMth(mthNodesRef(methods)); } @Override public void visitFieldsUsage(FieldNode fld, List<MethodNode> methods) { data.getFieldData(fld).setUsage(mthNodesRef(methods)); } @Override public void visitMethodsUsage(MethodNode mth, List<MethodNode> methods) { data.getMethodData(mth).setUsage(mthNodesRef(methods)); } @Override public void visitComplete() { data.collectClassesWithoutData(); } private List<String> clsNodesRef(List<ClassNode> usage) { return Utils.collectionMap(usage, ClassNode::getRawName); } private List<MthRef> mthNodesRef(List<MethodNode> methods) { return Utils.collectionMap(methods, m -> data.getMethodData(m).getMthRef()); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/usage/ClsUsageData.java
jadx-gui/src/main/java/jadx/gui/cache/usage/ClsUsageData.java
package jadx.gui.cache.usage; import java.util.HashMap; import java.util.List; import java.util.Map; final class ClsUsageData { private final String rawName; private List<String> clsDeps; private List<String> clsUsage; private List<MthRef> clsUseInMth; private final Map<String, FldUsageData> fldUsage = new HashMap<>(); private final Map<String, MthUsageData> mthUsage = new HashMap<>(); ClsUsageData(String rawName) { this.rawName = rawName; } public String getRawName() { return rawName; } public List<String> getClsDeps() { return clsDeps; } public void setClsDeps(List<String> clsDeps) { this.clsDeps = clsDeps; } public List<String> getClsUsage() { return clsUsage; } public void setClsUsage(List<String> clsUsage) { this.clsUsage = clsUsage; } public List<MthRef> getClsUseInMth() { return clsUseInMth; } public void setClsUseInMth(List<MthRef> clsUseInMth) { this.clsUseInMth = clsUseInMth; } public Map<String, FldUsageData> getFldUsage() { return fldUsage; } public Map<String, MthUsageData> getMthUsage() { return mthUsage; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/usage/MthUsageData.java
jadx-gui/src/main/java/jadx/gui/cache/usage/MthUsageData.java
package jadx.gui.cache.usage; import java.util.List; final class MthUsageData { private final MthRef mthRef; private List<MthRef> usage; public MthUsageData(MthRef mthRef) { this.mthRef = mthRef; } public MthRef getMthRef() { return mthRef; } public List<MthRef> getUsage() { return usage; } public void setUsage(List<MthRef> usage) { this.usage = usage; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/usage/MthRef.java
jadx-gui/src/main/java/jadx/gui/cache/usage/MthRef.java
package jadx.gui.cache.usage; final class MthRef { private final String cls; private final String shortId; MthRef(String cls, String shortId) { this.cls = cls; this.shortId = shortId; } public String getCls() { return cls; } public String getShortId() { return shortId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof MthRef)) { return false; } MthRef other = (MthRef) o; return cls.equals(other.cls) && shortId.equals(other.shortId); } @Override public int hashCode() { return 31 * cls.hashCode() + shortId.hashCode(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/usage/FldUsageData.java
jadx-gui/src/main/java/jadx/gui/cache/usage/FldUsageData.java
package jadx.gui.cache.usage; import java.util.List; final class FldUsageData { private final FldRef fldRef; private List<MthRef> usage; public FldUsageData(FldRef fldRef) { this.fldRef = fldRef; } public FldRef getFldRef() { return fldRef; } public List<MthRef> getUsage() { return usage; } public void setUsage(List<MthRef> usage) { this.usage = usage; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/cache/usage/UsageCacheMode.java
jadx-gui/src/main/java/jadx/gui/cache/usage/UsageCacheMode.java
package jadx.gui.cache.usage; public enum UsageCacheMode { NONE, MEMORY, DISK }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JClass.java
jadx-gui/src/main/java/jadx/gui/treemodel/JClass.java
package jadx.gui.treemodel; import java.util.List; import java.util.Set; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JPopupMenu; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import jadx.api.ICodeInfo; import jadx.api.JavaClass; import jadx.api.JavaField; import jadx.api.JavaMethod; import jadx.api.JavaNode; import jadx.api.data.ICodeRename; import jadx.api.data.impl.JadxCodeRename; import jadx.api.data.impl.JadxNodeRef; import jadx.core.deobf.NameMapper; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.info.AccessInfo; import jadx.core.dex.nodes.ICodeNode; import jadx.gui.jobs.SimpleTask; import jadx.gui.ui.MainWindow; import jadx.gui.ui.codearea.ClassCodeContentPanel; import jadx.gui.ui.panel.ContentPanel; import jadx.gui.ui.popupmenu.JClassPopupMenu; import jadx.gui.ui.tab.TabbedPane; import jadx.gui.utils.CacheObject; import jadx.gui.utils.Icons; import jadx.gui.utils.JNodeCache; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public class JClass extends JLoadableNode implements JRenameNode { private static final long serialVersionUID = -1239986875244097177L; private static final ImageIcon ICON_CLASS_ABSTRACT = UiUtils.openSvgIcon("nodes/abstractClass"); private static final ImageIcon ICON_CLASS_PUBLIC = UiUtils.openSvgIcon("nodes/publicClass"); private static final ImageIcon ICON_CLASS_PRIVATE = UiUtils.openSvgIcon("nodes/privateClass"); private static final ImageIcon ICON_CLASS_PROTECTED = UiUtils.openSvgIcon("nodes/protectedClass"); private static final ImageIcon ICON_INTERFACE = UiUtils.openSvgIcon("nodes/interface"); private static final ImageIcon ICON_ENUM = UiUtils.openSvgIcon("nodes/enum"); private static final ImageIcon ICON_ANNOTATION = UiUtils.openSvgIcon("nodes/annotationtype"); private final transient JavaClass cls; private final transient JClass jParent; private final transient JNodeCache nodeCache; private transient boolean loaded; /** * Should be called only from JNodeCache! */ public JClass(JavaClass cls, JClass parent, JNodeCache nodeCache) { this.cls = cls; this.jParent = parent; this.loaded = parent != null; this.nodeCache = nodeCache; } public JavaClass getCls() { return cls; } @Override public boolean canRename() { return !cls.getClassNode().contains(AFlag.DONT_RENAME); } @Override public void loadNode() { getRootClass().load(); } @Override public synchronized @Nullable SimpleTask getLoadTask() { if (loaded) { return null; } JClass rootClass = getRootClass(); return new SimpleTask(NLS.str("progress.decompile"), () -> rootClass.getCls().getClassNode().decompile(), // run decompilation in background rootClass::load // load class internals and update UI ); } private synchronized void load() { if (loaded) { return; } cls.decompile(); loaded = true; update(); } public synchronized ICodeInfo reload(CacheObject cache) { cache.getNodeCache().removeWholeClass(cls); ICodeInfo codeInfo = cls.reload(); loaded = true; update(); return codeInfo; } public synchronized void unload(CacheObject cache) { cache.getNodeCache().removeWholeClass(cls); cls.unload(); loaded = false; } public synchronized void update() { removeAllChildren(); if (!loaded) { add(new TextNode(NLS.str("tree.loading"))); } else { for (JavaClass javaClass : cls.getInnerClasses()) { JClass innerCls = nodeCache.makeFrom(javaClass); add(innerCls); innerCls.update(); } for (JavaField f : cls.getFields()) { add(nodeCache.makeFrom(f)); } for (JavaMethod m : cls.getMethods()) { add(nodeCache.makeFrom(m)); } } } @Override public ICodeInfo getCodeInfo() { return cls.getCodeInfo(); } @Override public boolean hasContent() { return true; } @Override public ContentPanel getContentPanel(TabbedPane tabbedPane) { return new ClassCodeContentPanel(tabbedPane, this); } public String getSmali() { return cls.getSmali(); } @Override public String getSyntaxName() { return SyntaxConstants.SYNTAX_STYLE_JAVA; } @Override public JPopupMenu onTreePopupMenu(MainWindow mainWindow) { return new JClassPopupMenu(mainWindow, this); } @Override public Icon getIcon() { AccessInfo accessInfo = cls.getAccessInfo(); if (accessInfo.isEnum()) { return ICON_ENUM; } if (accessInfo.isAnnotation()) { return ICON_ANNOTATION; } if (accessInfo.isInterface()) { return ICON_INTERFACE; } if (accessInfo.isAbstract()) { return ICON_CLASS_ABSTRACT; } if (accessInfo.isProtected()) { return ICON_CLASS_PROTECTED; } if (accessInfo.isPrivate()) { return ICON_CLASS_PRIVATE; } if (accessInfo.isPublic()) { return ICON_CLASS_PUBLIC; } return Icons.CLASS; } @Override public JavaNode getJavaNode() { return cls; } @Override public ICodeNode getCodeNodeRef() { return cls.getClassNode(); } @Override public JClass getJParent() { return jParent; } @Override public JClass getRootClass() { if (jParent == null) { return this; } return jParent.getRootClass(); } @Override public String getName() { return cls.getName(); } public String getFullName() { return cls.getFullName(); } @Override public String getTitle() { return makeLongStringHtml(); } @Override public boolean isValidName(String newName) { if (NameMapper.isValidIdentifier(newName)) { return true; } if (cls.isInner()) { // disallow to change package for inner classes return false; } if (NameMapper.isValidFullIdentifier(newName)) { return true; } // moving to default pkg return newName.startsWith(".") && NameMapper.isValidIdentifier(newName.substring(1)); } @Override public ICodeRename buildCodeRename(String newName, Set<ICodeRename> renames) { return new JadxCodeRename(JadxNodeRef.forCls(cls), newName); } @Override public void removeAlias() { // reset only short name, package name should be reset explicitly using PackageNode cls.getClassNode().rename(""); } @Override public void addUpdateNodes(List<JavaNode> toUpdate) { toUpdate.add(cls); toUpdate.addAll(cls.getUseIn()); } @Override public void reload(MainWindow mainWindow) { // TODO: rebuild packages only if class package has been changed mainWindow.reloadTreePreservingState(); } @Override public int hashCode() { return cls.hashCode(); } @Override public boolean equals(Object obj) { return this == obj || obj instanceof JClass && cls.equals(((JClass) obj).cls); } @Override public String makeString() { return cls.getName(); } @Override public String makeLongString() { return cls.getFullName(); } public int compareToCls(@NotNull JClass otherCls) { return this.getCls().getRawName().compareTo(otherCls.getCls().getRawName()); } @Override public int compareTo(@NotNull JNode other) { if (other instanceof JClass) { return compareToCls((JClass) other); } if (other instanceof JMethod) { int cmp = compareToCls(other.getJParent()); if (cmp != 0) { return cmp; } return -1; } return super.compareTo(other); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JInputFiles.java
jadx-gui/src/main/java/jadx/gui/treemodel/JInputFiles.java
package jadx.gui.treemodel; import java.nio.file.Path; import java.util.List; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JPopupMenu; import jadx.gui.ui.MainWindow; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; import jadx.gui.utils.ui.SimpleMenuItem; public class JInputFiles extends JNode { private static final ImageIcon INPUT_FILES_ICON = UiUtils.openSvgIcon("nodes/moduleDirectory"); public JInputFiles(List<Path> files) { for (Path file : files) { String fileName = file.getFileName().toString(); if (fileName.endsWith(".smali")) { add(new JInputSmaliFile(file)); } else { add(new JInputFile(file)); } } } @Override public JPopupMenu onTreePopupMenu(MainWindow mainWindow) { JPopupMenu menu = new JPopupMenu(); menu.add(new SimpleMenuItem(NLS.str("popup.add_files"), mainWindow::addFiles)); return menu; } @Override public JClass getJParent() { return null; } @Override public Icon getIcon() { return INPUT_FILES_ICON; } @Override public String getID() { return "JInputFiles"; } @Override public String makeString() { return NLS.str("tree.input_files"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/TextNode.java
jadx-gui/src/main/java/jadx/gui/treemodel/TextNode.java
package jadx.gui.treemodel; import javax.swing.Icon; public class TextNode extends JNode { private static final long serialVersionUID = 2342749142368352232L; private final String label; public TextNode(String str) { this.label = str; } @Override public JClass getJParent() { return null; } @Override public Icon getIcon() { return null; } @Override public String makeString() { return label; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JInputSmaliFile.java
jadx-gui/src/main/java/jadx/gui/treemodel/JInputSmaliFile.java
package jadx.gui.treemodel; import java.nio.file.Path; import java.util.Objects; import javax.swing.Icon; import javax.swing.JPopupMenu; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeInfo; import jadx.api.impl.SimpleCodeInfo; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.files.FileUtils; import jadx.gui.ui.MainWindow; import jadx.gui.ui.codearea.AbstractCodeArea; import jadx.gui.ui.codearea.CodeContentPanel; import jadx.gui.ui.panel.ContentPanel; import jadx.gui.ui.tab.TabbedPane; import jadx.gui.utils.Icons; public class JInputSmaliFile extends JEditableNode { private static final Logger LOG = LoggerFactory.getLogger(JInputSmaliFile.class); private final Path filePath; public JInputSmaliFile(Path filePath) { this.filePath = Objects.requireNonNull(filePath); } @Override public JPopupMenu onTreePopupMenu(MainWindow mainWindow) { return JInputFile.buildInputFilePopupMenu(mainWindow, filePath); } @Override public boolean hasContent() { return true; } @Override public @Nullable ContentPanel getContentPanel(TabbedPane tabbedPane) { return new CodeContentPanel(tabbedPane, this); } @Override public String getSyntaxName() { return AbstractCodeArea.SYNTAX_STYLE_SMALI; } @Override public ICodeInfo getCodeInfo() { try { return new SimpleCodeInfo(FileUtils.readFile(filePath)); } catch (Exception e) { throw new JadxRuntimeException("Failed to read file: " + filePath.toAbsolutePath(), e); } } @Override public void save(String newContent) { try { FileUtils.writeFile(filePath, newContent); LOG.debug("File saved: {}", filePath.toAbsolutePath()); } catch (Exception e) { throw new JadxRuntimeException("Failed to write file: " + filePath.toAbsolutePath(), e); } } @Override public JClass getJParent() { return null; } @Override public Icon getIcon() { return Icons.FILE; } @Override public String makeString() { return filePath.getFileName().toString(); } @Override public String getTooltip() { return filePath.normalize().toAbsolutePath().toString(); } @Override public int hashCode() { return filePath.hashCode(); } @Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } return ((JInputSmaliFile) o).filePath.equals(filePath); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JRoot.java
jadx-gui/src/main/java/jadx/gui/treemodel/JRoot.java
package jadx.gui.treemodel; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.regex.Pattern; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.tree.TreeNode; import org.jetbrains.annotations.Nullable; import jadx.api.ResourceFile; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.gui.JadxWrapper; import jadx.gui.settings.JadxProject; import jadx.gui.treemodel.JResource.JResType; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public class JRoot extends JNode { private static final long serialVersionUID = 8888495789773527342L; private static final ImageIcon ROOT_ICON = UiUtils.openSvgIcon("nodes/rootPackageFolder"); private final transient JadxWrapper wrapper; private transient boolean flatPackages = false; private final List<JNode> customNodes = new ArrayList<>(); public JRoot(JadxWrapper wrapper) { this.wrapper = wrapper; } public final void update() { removeAllChildren(); add(new JInputs(wrapper)); add(new JSources(this, wrapper)); List<ResourceFile> resources = wrapper.getResources(); if (!resources.isEmpty()) { add(getHierarchyResources(resources)); } for (JNode customNode : customNodes) { add(customNode); } } private JResource getHierarchyResources(List<ResourceFile> resources) { JResource root = new JResource(null, NLS.str("tree.resources_title"), JResType.ROOT); String splitPathStr = Pattern.quote(File.separator); for (ResourceFile rf : resources) { String rfName; if (rf.getZipEntry() != null) { rfName = rf.getDeobfName(); } else { rfName = new File(rf.getDeobfName()).getName(); } String[] parts = new File(rfName).getPath().split(splitPathStr); JResource curRf = root; int count = parts.length; for (int i = 0; i < count - 1; i++) { String name = parts[i]; JResource subRF = getResourceByName(curRf, name); if (subRF == null) { subRF = new JResource(null, name, JResType.DIR); curRf.addSubNode(subRF); } curRf = subRF; } JResource leaf = new JResource(rf, rf.getDeobfName(), parts[count - 1], JResType.FILE); curRf.addSubNode(leaf); } root.sortSubNodes(); root.update(); return root; } private JResource getResourceByName(JResource rf, String name) { for (JResource sub : rf.getSubNodes()) { if (sub.getName().equals(name)) { return sub; } } return null; } public @Nullable JNode searchNode(JNode node) { Enumeration<?> en = this.breadthFirstEnumeration(); while (en.hasMoreElements()) { Object obj = en.nextElement(); if (node.equals(obj)) { return (JNode) obj; } } return null; } public JNode followStaticPath(String... path) { List<String> list = Arrays.asList(path); JNode node = getNodeByClsPath(this, 0, list); if (node == null) { throw new JadxRuntimeException("Incorrect static path in tree: " + list); } return node; } private static @Nullable JNode getNodeByClsPath(JNode start, int pos, List<String> path) { if (pos >= path.size()) { return start; } String clsName = path.get(pos); Enumeration<TreeNode> en = start.children(); while (en.hasMoreElements()) { JNode node = (JNode) en.nextElement(); if (node.getClass().getSimpleName().equals(clsName)) { return getNodeByClsPath(node, pos + 1, path); } } return null; } public boolean isFlatPackages() { return flatPackages; } public void setFlatPackages(boolean flatPackages) { if (this.flatPackages != flatPackages) { this.flatPackages = flatPackages; update(); } } public void replaceCustomNode(@Nullable JNode node) { if (node == null) { return; } Class<?> nodeCls = node.getClass(); customNodes.removeIf(n -> n.getClass().equals(nodeCls)); customNodes.add(node); } public List<JNode> getCustomNodes() { return customNodes; } @Override public Icon getIcon() { return ROOT_ICON; } @Override public JClass getJParent() { return null; } @Override public String getID() { return "JRoot"; } @Override public String makeString() { JadxProject project = wrapper.getProject(); if (project.getProjectPath() != null) { return project.getName(); } List<Path> paths = project.getFilePaths(); int count = paths.size(); if (count == 0) { return "File not open"; } if (count == 1) { Path fileNamePath = paths.get(0).getFileName(); if (fileNamePath != null) { return fileNamePath.toString(); } return paths.get(0).toString(); } return count + " files"; } @Override public String getTooltip() { List<Path> paths = wrapper.getProject().getFilePaths(); int count = paths.size(); if (count < 2) { return null; } // Show list of loaded files (full path) StringBuilder sb = new StringBuilder("<html>"); for (Path p : paths) { sb.append(UiUtils.escapeHtml(p.toString())); sb.append("<br>"); } sb.append("</html>"); 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-gui/src/main/java/jadx/gui/treemodel/JRenameNode.java
jadx-gui/src/main/java/jadx/gui/treemodel/JRenameNode.java
package jadx.gui.treemodel; import java.util.List; import java.util.Set; import javax.swing.Icon; import jadx.api.JavaNode; import jadx.api.data.ICodeRename; import jadx.gui.ui.MainWindow; public interface JRenameNode { JavaNode getJavaNode(); String getTitle(); String getName(); Icon getIcon(); boolean canRename(); default JRenameNode replace() { return this; } ICodeRename buildCodeRename(String newName, Set<ICodeRename> renames); boolean isValidName(String newName); void removeAlias(); void addUpdateNodes(List<JavaNode> toUpdate); void reload(MainWindow mainWindow); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JNode.java
jadx-gui/src/main/java/jadx/gui/treemodel/JNode.java
package jadx.gui.treemodel; import java.util.Comparator; import java.util.Enumeration; import java.util.List; import java.util.function.Predicate; import javax.swing.JPopupMenu; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeNode; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import jadx.api.ICodeInfo; import jadx.api.JavaNode; import jadx.api.gui.tree.ITreeNode; import jadx.api.metadata.ICodeNodeRef; import jadx.api.resources.ResourceContentType; import jadx.core.utils.ListUtils; import jadx.gui.ui.MainWindow; import jadx.gui.ui.panel.ContentPanel; import jadx.gui.ui.tab.TabbedPane; public abstract class JNode extends DefaultMutableTreeNode implements ITreeNode, Comparable<JNode> { private static final long serialVersionUID = -5154479091781041008L; public abstract JClass getJParent(); /** * Return top level JClass or self if already at top. */ public JClass getRootClass() { return null; } public JavaNode getJavaNode() { return null; } @Override public ICodeNodeRef getCodeNodeRef() { return null; } public boolean hasContent() { return false; } public @Nullable ContentPanel getContentPanel(TabbedPane tabbedPane) { return null; } public String getSyntaxName() { return SyntaxConstants.SYNTAX_STYLE_NONE; } public ICodeInfo getCodeInfo() { return ICodeInfo.EMPTY; } public ResourceContentType getContentType() { return ResourceContentType.CONTENT_TEXT; } public boolean isEditable() { return false; } @Override public String getName() { JavaNode javaNode = getJavaNode(); if (javaNode == null) { return null; } return javaNode.getName(); } public boolean supportsQuickTabs() { return true; } public @Nullable JPopupMenu onTreePopupMenu(MainWindow mainWindow) { return null; } @Override public String getID() { return makeString(); } public abstract String makeString(); public String makeStringHtml() { return makeString(); } public String makeDescString() { return null; } public boolean hasDescString() { return false; } public String makeLongString() { return makeString(); } public String makeLongStringHtml() { return makeLongString(); } public boolean disableHtml() { return true; } public int getPos() { JavaNode javaNode = getJavaNode(); if (javaNode == null) { return -1; } return javaNode.getDefPos(); } public String getTooltip() { return makeLongStringHtml(); } public @Nullable JNode searchNode(Predicate<JNode> filter) { Enumeration<?> en = this.children(); while (en.hasMoreElements()) { JNode node = (JNode) en.nextElement(); if (filter.test(node)) { return node; } } return null; } /** * Remove and return first found node */ public @Nullable JNode removeNode(Predicate<JNode> filter) { Enumeration<?> en = this.children(); while (en.hasMoreElements()) { JNode node = (JNode) en.nextElement(); if (filter.test(node)) { this.remove(node); return node; } } return null; } public List<TreeNode> childrenList() { return ListUtils.enumerationToList(this.children()); } private static final Comparator<JNode> COMPARATOR = Comparator .comparing(JNode::makeLongString) .thenComparingInt(JNode::getPos); @Override public int compareTo(@NotNull JNode other) { return COMPARATOR.compare(this, other); } @Override public String toString() { return makeString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JResSearchNode.java
jadx-gui/src/main/java/jadx/gui/treemodel/JResSearchNode.java
package jadx.gui.treemodel; import javax.swing.Icon; import jadx.core.utils.StringUtils; public class JResSearchNode extends JNode { private static final long serialVersionUID = -2222084945157778639L; private final transient JResource resNode; private final transient String text; private final transient int pos; public JResSearchNode(JResource resNode, String text, int pos) { this.pos = pos; this.text = text; this.resNode = resNode; } public JResource getResNode() { return resNode; } public int getPos() { return pos; } @Override public String makeDescString() { return text; } @Override public JClass getJParent() { return resNode.getJParent(); } @Override public String makeLongStringHtml() { return getName(); } @Override public Icon getIcon() { return resNode.getIcon(); } @Override public String getName() { return resNode.getName(); } @Override public String makeString() { return resNode.makeString(); } @Override public boolean hasDescString() { return !StringUtils.isEmpty(text); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JInputScripts.java
jadx-gui/src/main/java/jadx/gui/treemodel/JInputScripts.java
package jadx.gui.treemodel; import java.nio.file.Path; import java.util.List; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JPopupMenu; import jadx.gui.ui.MainWindow; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; import jadx.gui.utils.ui.SimpleMenuItem; public class JInputScripts extends JNode { private static final ImageIcon INPUT_SCRIPTS_ICON = UiUtils.openSvgIcon("nodes/scriptsModel"); public JInputScripts(List<Path> scripts) { for (Path script : scripts) { add(new JInputScript(script)); } } @Override public JPopupMenu onTreePopupMenu(MainWindow mainWindow) { JPopupMenu menu = new JPopupMenu(); menu.add(new SimpleMenuItem(NLS.str("popup.add_scripts"), mainWindow::addFiles)); menu.add(new SimpleMenuItem(NLS.str("popup.new_script"), mainWindow::addNewScript)); return menu; } @Override public JClass getJParent() { return null; } @Override public Icon getIcon() { return INPUT_SCRIPTS_ICON; } @Override public String getID() { return "JInputScripts"; } @Override public String makeString() { return NLS.str("tree.input_scripts"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/CodeNode.java
jadx-gui/src/main/java/jadx/gui/treemodel/CodeNode.java
package jadx.gui.treemodel; import javax.swing.Icon; import org.jetbrains.annotations.NotNull; import jadx.api.JavaNode; public class CodeNode extends JNode { private static final long serialVersionUID = 1658650786734966545L; private final transient JClass rootCls; private final transient JNode jNode; private final transient String line; private final transient int pos; public CodeNode(JClass rootCls, JNode jNode, String lineStr, int pos) { this.rootCls = rootCls; this.jNode = jNode; this.line = lineStr; this.pos = pos; } @Override public Icon getIcon() { return jNode.getIcon(); } @Override public JavaNode getJavaNode() { return jNode.getJavaNode(); } @Override public JClass getJParent() { return getRootClass(); } @Override public JClass getRootClass() { return rootCls; } @Override public String makeDescString() { return line; } @Override public boolean hasDescString() { return true; } @Override public String makeString() { return jNode.makeString(); } @Override public String makeStringHtml() { return jNode.makeStringHtml(); } @Override public String makeLongString() { return jNode.makeLongString(); } @Override public String makeLongStringHtml() { return jNode.makeLongStringHtml(); } @Override public boolean disableHtml() { return jNode.disableHtml(); } @Override public String getSyntaxName() { return jNode.getSyntaxName(); } @Override public int getPos() { return pos; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof CodeNode)) { return false; } CodeNode codeNode = (CodeNode) o; return jNode.equals(codeNode.jNode); } @Override public int hashCode() { return jNode.hashCode(); } @Override public int compareTo(@NotNull JNode other) { if (other instanceof CodeNode) { return jNode.compareTo(((CodeNode) other).jNode); } return super.compareTo(other); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JInputScript.java
jadx-gui/src/main/java/jadx/gui/treemodel/JInputScript.java
package jadx.gui.treemodel; import java.nio.file.Path; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JPopupMenu; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeInfo; import jadx.api.impl.SimpleCodeInfo; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.files.FileUtils; import jadx.gui.plugins.script.ScriptContentPanel; import jadx.gui.ui.MainWindow; import jadx.gui.ui.panel.ContentPanel; import jadx.gui.ui.tab.TabbedPane; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; import jadx.gui.utils.ui.SimpleMenuItem; public class JInputScript extends JEditableNode { private static final Logger LOG = LoggerFactory.getLogger(JInputScript.class); private static final ImageIcon SCRIPT_ICON = UiUtils.openSvgIcon("nodes/kotlin_script"); private final Path scriptPath; private final String name; public JInputScript(Path scriptPath) { this.scriptPath = scriptPath; this.name = scriptPath.getFileName().toString().replace(".jadx.kts", ""); } @Override public boolean hasContent() { return true; } @Override public ContentPanel getContentPanel(TabbedPane tabbedPane) { return new ScriptContentPanel(tabbedPane, this); } @Override public @NotNull ICodeInfo getCodeInfo() { try { return new SimpleCodeInfo(FileUtils.readFile(scriptPath)); } catch (Exception e) { throw new JadxRuntimeException("Failed to read script file: " + scriptPath.toAbsolutePath(), e); } } @Override public void save(String newContent) { try { FileUtils.writeFile(scriptPath, newContent); LOG.debug("Script saved: {}", scriptPath.toAbsolutePath()); } catch (Exception e) { throw new JadxRuntimeException("Failed to write script file: " + scriptPath.toAbsolutePath(), e); } } @Override public JPopupMenu onTreePopupMenu(MainWindow mainWindow) { JPopupMenu menu = new JPopupMenu(); menu.add(new SimpleMenuItem(NLS.str("popup.add_scripts"), mainWindow::addFiles)); menu.add(new SimpleMenuItem(NLS.str("popup.new_script"), mainWindow::addNewScript)); menu.add(new SimpleMenuItem(NLS.str("popup.remove"), () -> mainWindow.removeInput(scriptPath))); menu.add(new SimpleMenuItem(NLS.str("popup.rename"), () -> mainWindow.renameInput(scriptPath))); return menu; } @Override public String getSyntaxName() { return SyntaxConstants.SYNTAX_STYLE_KOTLIN; } @Override public JClass getJParent() { return null; } @Override public Icon getIcon() { return SCRIPT_ICON; } @Override public String getName() { return name; } @Override public String makeString() { return name; } @Override public String getTooltip() { return scriptPath.normalize().toAbsolutePath().toString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JResource.java
jadx-gui/src/main/java/jadx/gui/treemodel/JResource.java
package jadx.gui.treemodel; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JPopupMenu; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.jetbrains.annotations.Nullable; import jadx.api.ICodeInfo; import jadx.api.ResourceFile; import jadx.api.ResourceType; import jadx.api.ResourcesLoader; import jadx.api.impl.SimpleCodeInfo; import jadx.api.resources.ResourceContentType; import jadx.core.utils.ListUtils; import jadx.core.utils.Utils; import jadx.core.xmlgen.ResContainer; import jadx.gui.jobs.SimpleTask; import jadx.gui.ui.MainWindow; import jadx.gui.ui.codearea.AbstractCodeArea; import jadx.gui.ui.codearea.BinaryContentPanel; import jadx.gui.ui.codearea.CodeContentPanel; import jadx.gui.ui.panel.ContentPanel; import jadx.gui.ui.panel.FontPanel; import jadx.gui.ui.panel.ImagePanel; import jadx.gui.ui.popupmenu.JResourcePopupMenu; import jadx.gui.ui.tab.TabbedPane; import jadx.gui.utils.Icons; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; import jadx.gui.utils.res.ResTableHelper; public class JResource extends JLoadableNode { private static final long serialVersionUID = -201018424302612434L; private static final ImageIcon ROOT_ICON = UiUtils.openSvgIcon("nodes/resourcesRoot"); private static final ImageIcon ARSC_ICON = UiUtils.openSvgIcon("nodes/resourceBundle"); private static final ImageIcon XML_ICON = UiUtils.openSvgIcon("nodes/xml"); private static final ImageIcon IMAGE_ICON = UiUtils.openSvgIcon("nodes/ImagesFileType"); private static final ImageIcon SO_ICON = UiUtils.openSvgIcon("nodes/binaryFile"); private static final ImageIcon MANIFEST_ICON = UiUtils.openSvgIcon("nodes/manifest"); private static final ImageIcon JAVA_ICON = UiUtils.openSvgIcon("nodes/java"); private static final ImageIcon APK_ICON = UiUtils.openSvgIcon("nodes/archiveApk"); private static final ImageIcon AUDIO_ICON = UiUtils.openSvgIcon("nodes/audioFile"); private static final ImageIcon VIDEO_ICON = UiUtils.openSvgIcon("nodes/videoFile"); private static final ImageIcon FONT_ICON = UiUtils.openSvgIcon("nodes/fontFile"); private static final ImageIcon HTML_ICON = UiUtils.openSvgIcon("nodes/html"); private static final ImageIcon JSON_ICON = UiUtils.openSvgIcon("nodes/json"); private static final ImageIcon TEXT_ICON = UiUtils.openSvgIcon("nodes/text"); private static final ImageIcon ARCHIVE_ICON = UiUtils.openSvgIcon("nodes/archive"); private static final ImageIcon UNKNOWN_ICON = UiUtils.openSvgIcon("nodes/unknown"); public static final Comparator<JResource> RESOURCES_COMPARATOR = Comparator.<JResource>comparingInt(r -> r.type.ordinal()) .thenComparing(JResource::getName, String.CASE_INSENSITIVE_ORDER); public enum JResType { ROOT, DIR, FILE } private final transient String name; private final transient String shortName; private final transient JResType type; private final transient ResourceFile resFile; private transient volatile boolean loaded; private transient List<JResource> subNodes = Collections.emptyList(); private transient ICodeInfo content = ICodeInfo.EMPTY; public JResource(ResourceFile resFile, String name, JResType type) { this(resFile, name, name, type); } public JResource(ResourceFile resFile, String name, String shortName, JResType type) { this.resFile = resFile; this.name = name; this.shortName = shortName; this.type = type; this.loaded = false; } public synchronized void update() { removeAllChildren(); if (Utils.isEmpty(subNodes)) { if (type == JResType.DIR || type == JResType.ROOT || resFile.getType() == ResourceType.ARSC) { // fake leaf to force show expand button // real sub nodes will load on expand in loadNode() method add(new TextNode(NLS.str("tree.loading"))); } } else { for (JResource res : subNodes) { res.update(); add(res); } if (type != JResType.FILE) { // no content, nothing to load loaded = true; } } } @Override public synchronized void loadNode() { getCodeInfo(); update(); } @Override public synchronized SimpleTask getLoadTask() { if (loaded) { return null; } return new SimpleTask(NLS.str("progress.load"), this::getCodeInfo, this::update); } @Override public String getName() { return name; } public JResType getType() { return type; } public List<JResource> getSubNodes() { return subNodes; } public void addSubNode(JResource node) { subNodes = ListUtils.safeAdd(subNodes, node); } public void sortSubNodes() { sortResNodes(subNodes); } private static void sortResNodes(List<JResource> nodes) { if (Utils.notEmpty(nodes)) { nodes.forEach(JResource::sortSubNodes); nodes.sort(RESOURCES_COMPARATOR); } } @Override public boolean hasContent() { return resFile != null; } @Override public @Nullable ContentPanel getContentPanel(TabbedPane tabbedPane) { if (resFile == null) { return null; } // TODO: allow to register custom viewers switch (resFile.getType()) { case IMG: return new ImagePanel(tabbedPane, this); case FONT: return new FontPanel(tabbedPane, this); } if (getContentType() == ResourceContentType.CONTENT_BINARY) { return new BinaryContentPanel(tabbedPane, this, false); } if (getSyntaxByExtension(resFile.getDeobfName()) != null) { return new CodeContentPanel(tabbedPane, this); } // unknown file type, show both text and binary return new BinaryContentPanel(tabbedPane, this, true); } @Override public JPopupMenu onTreePopupMenu(MainWindow mainWindow) { return new JResourcePopupMenu(mainWindow, this); } @Override public synchronized ICodeInfo getCodeInfo() { if (loaded) { return content; } ICodeInfo codeInfo = loadContent(); content = codeInfo; loaded = true; return codeInfo; } @Override public ResourceContentType getContentType() { if (type == JResType.FILE) { return resFile.getType().getContentType(); } return ResourceContentType.CONTENT_NONE; } private ICodeInfo loadContent() { if (resFile == null || type != JResType.FILE) { return ICodeInfo.EMPTY; } ResContainer rc = resFile.loadContent(); if (rc == null) { return ICodeInfo.EMPTY; } if (rc.getDataType() == ResContainer.DataType.RES_TABLE) { ICodeInfo codeInfo = loadCurrentSingleRes(rc); List<JResource> nodes = ResTableHelper.buildTree(rc); sortResNodes(nodes); subNodes = nodes; UiUtils.uiRun(this::update); return codeInfo; } // single node return loadCurrentSingleRes(rc); } private ICodeInfo loadCurrentSingleRes(ResContainer rc) { switch (rc.getDataType()) { case TEXT: case RES_TABLE: return rc.getText(); case RES_LINK: try { ResourceFile resourceFile = rc.getResLink(); return ResourcesLoader.decodeStream(resourceFile, (size, is) -> { // TODO: check size before loading if (size > 10 * 1024 * 1024L) { return new SimpleCodeInfo("File too large for view"); } Charset charset; if (resourceFile.getType().getContentType() == ResourceContentType.CONTENT_TEXT) { charset = StandardCharsets.UTF_8; } else { // force one byte charset for binary data to have the same offsets as in a byte array charset = StandardCharsets.US_ASCII; } return ResourcesLoader.loadToCodeWriter(is, charset); }); } catch (Exception e) { return new SimpleCodeInfo("Failed to load resource file:\n" + Utils.getStackTrace(e)); } case DECODED_DATA: default: return new SimpleCodeInfo("Unexpected resource type: " + rc); } } @Override public String getSyntaxName() { if (resFile == null) { return null; } switch (resFile.getType()) { case CODE: return super.getSyntaxName(); case MANIFEST: case XML: case ARSC: return SyntaxConstants.SYNTAX_STYLE_XML; default: String syntax = getSyntaxByExtension(resFile.getDeobfName()); if (syntax != null) { return syntax; } return super.getSyntaxName(); } } private static final Map<String, String> EXTENSION_TO_FILE_SYNTAX = jadx.core.utils.Utils.newConstStringMap( "java", SyntaxConstants.SYNTAX_STYLE_JAVA, "smali", AbstractCodeArea.SYNTAX_STYLE_SMALI, "js", SyntaxConstants.SYNTAX_STYLE_JAVASCRIPT, "ts", SyntaxConstants.SYNTAX_STYLE_TYPESCRIPT, "json", SyntaxConstants.SYNTAX_STYLE_JSON, "css", SyntaxConstants.SYNTAX_STYLE_CSS, "less", SyntaxConstants.SYNTAX_STYLE_LESS, "html", SyntaxConstants.SYNTAX_STYLE_HTML, "xml", SyntaxConstants.SYNTAX_STYLE_XML, "yaml", SyntaxConstants.SYNTAX_STYLE_YAML, "properties", SyntaxConstants.SYNTAX_STYLE_PROPERTIES_FILE, "ini", SyntaxConstants.SYNTAX_STYLE_INI, "sql", SyntaxConstants.SYNTAX_STYLE_SQL); private String getSyntaxByExtension(String name) { int dot = name.lastIndexOf('.'); if (dot == -1) { return null; } String ext = name.substring(dot + 1); return EXTENSION_TO_FILE_SYNTAX.get(ext); } @Override public Icon getIcon() { switch (type) { case ROOT: return ROOT_ICON; case DIR: return Icons.FOLDER; case FILE: ResourceType resType = resFile.getType(); switch (resType) { case MANIFEST: return MANIFEST_ICON; case ARSC: return ARSC_ICON; case XML: return XML_ICON; case IMG: return IMAGE_ICON; case LIB: return SO_ICON; case CODE: return JAVA_ICON; case APK: return APK_ICON; case VIDEOS: return VIDEO_ICON; case SOUNDS: return AUDIO_ICON; case FONT: return FONT_ICON; case HTML: return HTML_ICON; case JSON: return JSON_ICON; case TEXT: return TEXT_ICON; case ARCHIVE: return ARCHIVE_ICON; case UNKNOWN: return UNKNOWN_ICON; } return UNKNOWN_ICON; } return Icons.FILE; } public static boolean isSupportedForView(ResourceType type) { switch (type) { case SOUNDS: case VIDEOS: case ARCHIVE: case APK: return false; case MANIFEST: case XML: case ARSC: case IMG: case LIB: case FONT: case TEXT: case JSON: case HTML: case UNKNOWN: return true; } return true; } public static boolean isOpenInExternalTool(ResourceType type) { switch (type) { case SOUNDS: case VIDEOS: return true; default: return false; } } public ResourceFile getResFile() { return resFile; } @Override public JClass getJParent() { return null; } @Override public String getID() { if (type == JResType.ROOT) { return "JResources"; } return makeString(); } @Override public String makeString() { return shortName; } @Override public String makeLongString() { return name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } JResource other = (JResource) o; return name.equals(other.name) && type.equals(other.type); } @Override public int hashCode() { return name.hashCode() + 31 * type.ordinal(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JLoadableNode.java
jadx-gui/src/main/java/jadx/gui/treemodel/JLoadableNode.java
package jadx.gui.treemodel; import java.util.function.Predicate; import org.jetbrains.annotations.Nullable; import jadx.gui.jobs.IBackgroundTask; public abstract class JLoadableNode extends JNode { private static final long serialVersionUID = 5543590584166374958L; public abstract void loadNode(); public abstract @Nullable IBackgroundTask getLoadTask(); @Override public @Nullable JNode searchNode(Predicate<JNode> filter) { loadNode(); return super.searchNode(filter); } @Override public @Nullable JNode removeNode(Predicate<JNode> filter) { loadNode(); return super.removeNode(filter); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JField.java
jadx-gui/src/main/java/jadx/gui/treemodel/JField.java
package jadx.gui.treemodel; import java.util.Comparator; import java.util.List; import java.util.Set; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JPopupMenu; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.jetbrains.annotations.NotNull; import jadx.api.JavaField; import jadx.api.JavaNode; import jadx.api.data.ICodeRename; import jadx.api.data.impl.JadxCodeRename; import jadx.api.data.impl.JadxNodeRef; import jadx.api.metadata.ICodeNodeRef; import jadx.core.deobf.NameMapper; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.info.AccessInfo; import jadx.gui.ui.MainWindow; import jadx.gui.ui.dialog.RenameDialog; import jadx.gui.utils.Icons; import jadx.gui.utils.UiUtils; public class JField extends JNode implements JRenameNode { private static final long serialVersionUID = 1712572192106793359L; private static final ImageIcon ICON_FLD_PRI = UiUtils.openSvgIcon("nodes/privateField"); private static final ImageIcon ICON_FLD_PRO = UiUtils.openSvgIcon("nodes/protectedField"); private static final ImageIcon ICON_FLD_PUB = UiUtils.openSvgIcon("nodes/publicField"); private final transient JavaField field; private final transient JClass jParent; /** * Should be called only from JNodeCache! */ public JField(JavaField javaField, JClass jClass) { this.field = javaField; this.jParent = jClass; } public JavaField getJavaField() { return (JavaField) getJavaNode(); } @Override public JavaNode getJavaNode() { return field; } @Override public ICodeNodeRef getCodeNodeRef() { return field.getFieldNode(); } @Override public JClass getJParent() { return jParent; } @Override public JClass getRootClass() { return jParent.getRootClass(); } @Override public boolean canRename() { return !field.getFieldNode().contains(AFlag.DONT_RENAME); } @Override public JPopupMenu onTreePopupMenu(MainWindow mainWindow) { return RenameDialog.buildRenamePopup(mainWindow, this); } @Override public String getTitle() { return makeLongStringHtml(); } @Override public ICodeRename buildCodeRename(String newName, Set<ICodeRename> renames) { return new JadxCodeRename(JadxNodeRef.forFld(field), newName); } @Override public boolean isValidName(String newName) { return NameMapper.isValidIdentifier(newName); } @Override public void removeAlias() { field.removeAlias(); } @Override public void addUpdateNodes(List<JavaNode> toUpdate) { toUpdate.add(field); toUpdate.addAll(field.getUseIn()); } @Override public void reload(MainWindow mainWindow) { mainWindow.reloadTreePreservingState(); } @Override public Icon getIcon() { AccessInfo af = field.getAccessFlags(); return UiUtils.makeIcon(af, ICON_FLD_PUB, ICON_FLD_PRI, ICON_FLD_PRO, Icons.FIELD); } @Override public String getSyntaxName() { return SyntaxConstants.SYNTAX_STYLE_JAVA; } @Override public String makeString() { return UiUtils.typeFormat(field.getName(), field.getType()); } @Override public String makeStringHtml() { return UiUtils.typeFormatHtml(field.getName(), field.getType()); } @Override public String makeLongString() { return UiUtils.typeFormat(field.getFullName(), field.getType()); } @Override public String makeLongStringHtml() { return UiUtils.typeFormatHtml(field.getFullName(), field.getType()); } @Override public String getTooltip() { String fullType = UiUtils.escapeHtml(field.getType().toString()); return UiUtils.wrapHtml(fullType + ' ' + UiUtils.escapeHtml(field.getName())); } @Override public String makeDescString() { return UiUtils.typeStr(field.getType()) + " " + field.getName(); } @Override public boolean disableHtml() { return false; } @Override public boolean hasDescString() { return false; } @Override public int hashCode() { return field.hashCode(); } @Override public boolean equals(Object o) { return this == o || o instanceof JField && field.equals(((JField) o).field); } private static final Comparator<JField> COMPARATOR = Comparator .comparing(JField::getJParent) .thenComparing(JNode::getName) .thenComparingInt(JField::getPos); public int compareToFld(@NotNull JField other) { return COMPARATOR.compare(this, other); } @Override public int compareTo(@NotNull JNode other) { if (other instanceof JField) { return compareToFld(((JField) other)); } return super.compareTo(other); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/ApkSignatureNode.java
jadx-gui/src/main/java/jadx/gui/treemodel/ApkSignatureNode.java
package jadx.gui.treemodel; import java.io.File; import java.security.cert.Certificate; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.SwingUtilities; import javax.swing.SwingWorker; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.text.StringEscapeUtils; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.android.apksig.ApkVerifier; import jadx.api.ICodeInfo; import jadx.api.ResourceFile; import jadx.api.ResourceType; import jadx.api.impl.SimpleCodeInfo; import jadx.gui.JadxWrapper; import jadx.gui.ui.panel.ContentPanel; import jadx.gui.ui.panel.HtmlPanel; import jadx.gui.ui.tab.TabbedPane; import jadx.gui.utils.CertificateManager; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; import jadx.zip.IZipEntry; public class ApkSignatureNode extends JNode { private static final long serialVersionUID = -9121321926113143407L; private static final Logger LOG = LoggerFactory.getLogger(ApkSignatureNode.class); private static final ImageIcon CERTIFICATE_ICON = UiUtils.openSvgIcon("nodes/styleKeyPack"); private final transient File openFile; private ICodeInfo content; private volatile boolean loadingStarted = false; private static TabbedPane tabbedPane; @Nullable public static ApkSignatureNode getApkSignature(JadxWrapper wrapper) { // Only show the ApkSignature node if an AndroidManifest.xml is present. // Without a manifest the Google ApkVerifier refuses to work. File apkFile = null; for (ResourceFile resFile : wrapper.getResources()) { if (resFile.getType() == ResourceType.MANIFEST) { IZipEntry zipEntry = resFile.getZipEntry(); if (zipEntry != null) { apkFile = zipEntry.getZipFile(); break; } } } if (apkFile == null) { return null; } return new ApkSignatureNode(apkFile); } public ApkSignatureNode(File openFile) { this.openFile = openFile; } @Override public JClass getJParent() { return null; } @Override public Icon getIcon() { return CERTIFICATE_ICON; } @Override public String makeString() { return "APK signature"; } @Override public boolean hasContent() { return true; } @Override public ContentPanel getContentPanel(TabbedPane tabbedPane) { ApkSignatureNode.tabbedPane = tabbedPane; return new HtmlPanel(tabbedPane, this); } @Override public ICodeInfo getCodeInfo() { if (content != null) { return content; } // If loading hasn't started yet, start it. if (!loadingStarted) { loadingStarted = true; SwingUtilities.invokeLater(() -> { new ApkSignatureWorker(this).execute(); }); return new SimpleCodeInfo(StringEscapeUtils.escapeHtml4(NLS.str("apkSignature.loading"))); } return new SimpleCodeInfo(StringEscapeUtils.escapeHtml4(NLS.str("apkSignature.loading"))); } private void writeCertificate(StringEscapeUtils.Builder builder, Certificate cert) { CertificateManager certMgr = new CertificateManager(cert); builder.append("<blockquote><pre>"); builder.escape(certMgr.generateHeader()); builder.append("</pre><pre>"); builder.escape(certMgr.generatePublicKey()); builder.append("</pre><pre>"); builder.escape(certMgr.generateSignature()); builder.append("</pre><pre>"); builder.append(certMgr.generateFingerprint()); builder.append("</pre></blockquote>"); } private static void writeIssues(StringEscapeUtils.Builder builder, String issueType, List<ApkVerifier.IssueWithParams> issueList) { if (!issueList.isEmpty()) { builder.append("<h3>"); builder.escape(issueType); builder.append("</h3>"); builder.append("<blockquote>"); // Unprotected Zip entry issues are very common, handle them separately List<ApkVerifier.IssueWithParams> unprotIssues = issueList.stream() .filter(i -> i.getIssue() == ApkVerifier.Issue.JAR_SIG_UNPROTECTED_ZIP_ENTRY) .collect(Collectors.toList()); if (!unprotIssues.isEmpty()) { builder.append("<h4>"); builder.escape(NLS.str("apkSignature.unprotectedEntry")); builder.append("</h4><blockquote>"); for (ApkVerifier.IssueWithParams issue : unprotIssues) { builder.escape((String) issue.getParams()[0]); builder.append("<br>"); } builder.append("</blockquote>"); } List<ApkVerifier.IssueWithParams> remainingIssues = issueList.stream() .filter(i -> i.getIssue() != ApkVerifier.Issue.JAR_SIG_UNPROTECTED_ZIP_ENTRY) .collect(Collectors.toList()); if (!remainingIssues.isEmpty()) { builder.append("<pre>\n"); for (ApkVerifier.IssueWithParams issue : remainingIssues) { builder.escape(issue.toString()); builder.append("\n"); } builder.append("</pre>\n"); } builder.append("</blockquote>"); } } private static class ApkSignatureWorker extends SwingWorker<ICodeInfo, Void> { private final ApkSignatureNode node; public ApkSignatureWorker(ApkSignatureNode node) { this.node = node; } @Override protected ICodeInfo doInBackground() { LOG.debug("Starting APK signature verification for {}", node.openFile); ApkVerifier verifier = new ApkVerifier.Builder(node.openFile).build(); try { ApkVerifier.Result result = verifier.verify(); // Build HTML content StringEscapeUtils.Builder builder = StringEscapeUtils.builder(StringEscapeUtils.ESCAPE_HTML4); builder.append("<h1>APK signature verification result:</h1>"); builder.append("<p><b>"); if (result.isVerified()) { builder.escape(NLS.str("apkSignature.verificationSuccess")); } else { builder.escape(NLS.str("apkSignature.verificationFailed")); } builder.append("</b></p>"); final String err = NLS.str("apkSignature.errors"); final String warn = NLS.str("apkSignature.warnings"); final String sigSuccKey = "apkSignature.signatureSuccess"; final String sigFailKey = "apkSignature.signatureFailed"; ApkSignatureNode parentNode = node; writeIssues(builder, err, result.getErrors()); if (!result.getV1SchemeSigners().isEmpty()) { builder.append("<h2>"); builder.escape(NLS.str(result.isVerifiedUsingV1Scheme() ? sigSuccKey : sigFailKey, 1)); builder.append("</h2>\n"); builder.append("<blockquote>"); for (ApkVerifier.Result.V1SchemeSignerInfo signer : result.getV1SchemeSigners()) { builder.append("<h3>"); builder.escape(NLS.str("apkSignature.signer")); builder.append(" "); builder.escape(signer.getName()); builder.append(" ("); builder.escape(signer.getSignatureFileName()); builder.append(")"); builder.append("</h3>"); parentNode.writeCertificate(builder, signer.getCertificate()); writeIssues(builder, err, signer.getErrors()); writeIssues(builder, warn, signer.getWarnings()); } builder.append("</blockquote>"); } if (!result.getV2SchemeSigners().isEmpty()) { builder.append("<h2>"); builder.escape(NLS.str(result.isVerifiedUsingV2Scheme() ? sigSuccKey : sigFailKey, 2)); builder.append("</h2>\n"); builder.append("<blockquote>"); for (ApkVerifier.Result.V2SchemeSignerInfo signer : result.getV2SchemeSigners()) { builder.append("<h3>"); builder.escape(NLS.str("apkSignature.signer")); builder.append(" "); builder.append(Integer.toString(signer.getIndex() + 1)); builder.append("</h3>"); parentNode.writeCertificate(builder, signer.getCertificate()); writeIssues(builder, err, signer.getErrors()); writeIssues(builder, warn, signer.getWarnings()); } builder.append("</blockquote>"); } if (!result.getV3SchemeSigners().isEmpty()) { builder.append("<h2>"); builder.escape(NLS.str(result.isVerifiedUsingV3Scheme() ? sigSuccKey : sigFailKey, 3)); builder.append("</h2>\n"); builder.append("<blockquote>"); for (ApkVerifier.Result.V3SchemeSignerInfo signer : result.getV3SchemeSigners()) { builder.append("<h3>"); builder.escape(NLS.str("apkSignature.signer")); builder.append(" "); builder.append(Integer.toString(signer.getIndex() + 1)); builder.append("</h3>"); parentNode.writeCertificate(builder, signer.getCertificate()); writeIssues(builder, err, signer.getErrors()); writeIssues(builder, warn, signer.getWarnings()); } builder.append("</blockquote>"); } if (!result.getV31SchemeSigners().isEmpty()) { builder.append("<h2>"); builder.escape(NLS.str(result.isVerifiedUsingV31Scheme() ? sigSuccKey : sigFailKey, 31)); builder.append("</h2>\n"); builder.append("<blockquote>"); for (ApkVerifier.Result.V3SchemeSignerInfo signer : result.getV31SchemeSigners()) { builder.append("<h3>"); builder.escape(NLS.str("apkSignature.signer")); builder.append(" "); builder.append(Integer.toString(signer.getIndex() + 1)); builder.append("</h3>"); parentNode.writeCertificate(builder, signer.getCertificate()); writeIssues(builder, err, signer.getErrors()); writeIssues(builder, warn, signer.getWarnings()); } builder.append("</blockquote>"); } writeIssues(builder, warn, result.getWarnings()); return new SimpleCodeInfo(builder.toString()); } catch (Exception e) { LOG.error("Failed to verify APK signature for {}", node.openFile, e); StringEscapeUtils.Builder builder = StringEscapeUtils.builder(StringEscapeUtils.ESCAPE_HTML4); builder.append("<h1>"); builder.escape(NLS.str("apkSignature.exception")); builder.append("</h1><pre>"); builder.escape(ExceptionUtils.getStackTrace(e)); builder.append("</pre>"); return new SimpleCodeInfo(builder.toString()); } } @Override protected void done() { try { node.content = get(); if (tabbedPane != null) { ContentPanel panel = tabbedPane.getTabByNode(node); if (panel instanceof HtmlPanel) { ((HtmlPanel) panel).loadContent(node); } } else { LOG.warn("Could not find TabbedPane to refresh ApkSignatureNode panel."); } } catch (InterruptedException | ExecutionException e) { LOG.error("Error during APK signature verification SwingWorker", e); StringEscapeUtils.Builder builder = StringEscapeUtils.builder(StringEscapeUtils.ESCAPE_HTML4); builder.append("<h1>"); builder.escape(NLS.str("apkSignature.exception")); builder.append("</h1><pre>"); Throwable cause = (e instanceof ExecutionException) ? e.getCause() : e; builder.escape(ExceptionUtils.getStackTrace(cause)); builder.append("</pre>"); node.content = new SimpleCodeInfo(builder.toString()); if (tabbedPane != null) { ContentPanel panel = tabbedPane.getTabByNode(node); if (panel instanceof HtmlPanel) { ((HtmlPanel) panel).loadContent(node); } } } finally { node.loadingStarted = false; } } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JVariable.java
jadx-gui/src/main/java/jadx/gui/treemodel/JVariable.java
package jadx.gui.treemodel; import java.util.List; import java.util.Set; import javax.swing.Icon; import jadx.api.JavaNode; import jadx.api.JavaVariable; import jadx.api.data.ICodeRename; import jadx.api.data.impl.JadxCodeRef; import jadx.api.data.impl.JadxCodeRename; import jadx.api.data.impl.JadxNodeRef; import jadx.api.metadata.ICodeNodeRef; import jadx.core.deobf.NameMapper; import jadx.gui.ui.MainWindow; import jadx.gui.utils.UiUtils; public class JVariable extends JNode implements JRenameNode { private static final long serialVersionUID = -3002100457834453783L; private final JMethod jMth; private final JavaVariable var; public JVariable(JMethod jMth, JavaVariable var) { this.jMth = jMth; this.var = var; } public JavaVariable getJavaVarNode() { return var; } @Override public JavaNode getJavaNode() { return var; } @Override public JClass getRootClass() { return jMth.getRootClass(); } @Override public ICodeNodeRef getCodeNodeRef() { return var.getVarNode(); } @Override public JClass getJParent() { return jMth.getJParent(); } @Override public int getPos() { return var.getDefPos(); } @Override public Icon getIcon() { return null; } @Override public String makeString() { return var.getName(); } @Override public String makeLongString() { return var.getFullName(); } @Override public String makeLongStringHtml() { return UiUtils.typeFormatHtml(var.getName(), var.getType()); } @Override public boolean disableHtml() { return false; } @Override public String getTooltip() { String name = var.getName() + " (r" + var.getReg() + "v" + var.getSsa() + ")"; String fullType = UiUtils.escapeHtml(var.getType().toString()); return UiUtils.wrapHtml(fullType + ' ' + UiUtils.escapeHtml(name)); } @Override public boolean canRename() { return var.getName() != null; } @Override public String getTitle() { return makeLongStringHtml(); } @Override public boolean isValidName(String newName) { return NameMapper.isValidIdentifier(newName); } @Override public ICodeRename buildCodeRename(String newName, Set<ICodeRename> renames) { return new JadxCodeRename(JadxNodeRef.forMth(var.getMth()), JadxCodeRef.forVar(var), newName); } @Override public void removeAlias() { var.removeAlias(); } @Override public void addUpdateNodes(List<JavaNode> toUpdate) { toUpdate.add(var.getMth()); } @Override public void reload(MainWindow mainWindow) { } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JInputs.java
jadx-gui/src/main/java/jadx/gui/treemodel/JInputs.java
package jadx.gui.treemodel; import java.nio.file.Path; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.Icon; import javax.swing.ImageIcon; import jadx.core.utils.files.FileUtils; import jadx.gui.JadxWrapper; import jadx.gui.settings.JadxProject; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public class JInputs extends JNode { private static final ImageIcon INPUTS_ICON = UiUtils.openSvgIcon("nodes/projectStructure"); public JInputs(JadxWrapper wrapper) { JadxProject project = wrapper.getProject(); List<Path> inputs = project.getFilePaths(); List<Path> files = FileUtils.expandDirs(inputs); List<Path> scripts = new ArrayList<>(); Iterator<Path> it = files.iterator(); while (it.hasNext()) { Path file = it.next(); if (file.getFileName().toString().endsWith(".jadx.kts")) { scripts.add(file); it.remove(); } } add(new JInputFiles(files)); add(new JInputScripts(scripts)); } @Override public JClass getJParent() { return null; } @Override public Icon getIcon() { return INPUTS_ICON; } @Override public String getID() { return "JInputs"; } @Override public String makeString() { return NLS.str("tree.inputs_title"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JInputFile.java
jadx-gui/src/main/java/jadx/gui/treemodel/JInputFile.java
package jadx.gui.treemodel; import java.nio.file.Path; import java.util.Objects; import javax.swing.Icon; import javax.swing.JPopupMenu; import jadx.gui.ui.MainWindow; import jadx.gui.utils.Icons; import jadx.gui.utils.NLS; import jadx.gui.utils.ui.SimpleMenuItem; public class JInputFile extends JNode { private final Path filePath; public JInputFile(Path filePath) { this.filePath = Objects.requireNonNull(filePath); } @Override public JPopupMenu onTreePopupMenu(MainWindow mainWindow) { return buildInputFilePopupMenu(mainWindow, filePath); } public static JPopupMenu buildInputFilePopupMenu(MainWindow mainWindow, Path filePath) { JPopupMenu menu = new JPopupMenu(); menu.add(new SimpleMenuItem(NLS.str("popup.add_files"), mainWindow::addFiles)); menu.add(new SimpleMenuItem(NLS.str("popup.remove"), () -> mainWindow.removeInput(filePath))); menu.add(new SimpleMenuItem(NLS.str("popup.rename"), () -> mainWindow.renameInput(filePath))); return menu; } @Override public JClass getJParent() { return null; } @Override public Icon getIcon() { return Icons.FILE; } @Override public String makeString() { return filePath.getFileName().toString(); } @Override public String getTooltip() { return filePath.normalize().toAbsolutePath().toString(); } @Override public int hashCode() { return filePath.hashCode(); } @Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } return ((JInputFile) o).filePath.equals(filePath); } @Override public String toString() { return "JInputFile{" + filePath + '}'; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JSources.java
jadx-gui/src/main/java/jadx/gui/treemodel/JSources.java
package jadx.gui.treemodel; import java.util.List; import javax.swing.Icon; import javax.swing.ImageIcon; import jadx.gui.JadxWrapper; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; import jadx.gui.utils.pkgs.PackageHelper; public class JSources extends JNode { private static final long serialVersionUID = 8962924556824862801L; private static final ImageIcon ROOT_ICON = UiUtils.openSvgIcon("nodes/packageClasses"); private final transient JadxWrapper wrapper; private final transient boolean flatPackages; public JSources(JRoot jRoot, JadxWrapper wrapper) { this.flatPackages = jRoot.isFlatPackages(); this.wrapper = wrapper; update(); } public final void update() { removeAllChildren(); PackageHelper packageHelper = wrapper.getCache().getPackageHelper(); List<JPackage> roots = packageHelper.getRoots(flatPackages); for (JPackage rootPkg : roots) { rootPkg.update(); add(rootPkg); } } @Override public Icon getIcon() { return ROOT_ICON; } @Override public JClass getJParent() { return null; } @Override public String getID() { return "JSources"; } @Override public String makeString() { return NLS.str("tree.sources_title"); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JEditableNode.java
jadx-gui/src/main/java/jadx/gui/treemodel/JEditableNode.java
package jadx.gui.treemodel; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public abstract class JEditableNode extends JNode { private volatile boolean changed = false; private final List<Consumer<Boolean>> changeListeners = new ArrayList<>(); public abstract void save(String newContent); @Override public boolean isEditable() { return true; } public boolean isChanged() { return changed; } public void setChanged(boolean changed) { if (this.changed != changed) { this.changed = changed; for (Consumer<Boolean> changeListener : changeListeners) { changeListener.accept(changed); } } } public void addChangeListener(Consumer<Boolean> listener) { changeListeners.add(listener); listener.accept(changed); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/treemodel/JPackage.java
jadx-gui/src/main/java/jadx/gui/treemodel/JPackage.java
package jadx.gui.treemodel; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.swing.Icon; import javax.swing.JPopupMenu; import jadx.api.JavaNode; import jadx.api.JavaPackage; import jadx.gui.ui.MainWindow; import jadx.gui.ui.popupmenu.JPackagePopupMenu; import jadx.gui.utils.Icons; import static jadx.gui.utils.UiUtils.escapeHtml; import static jadx.gui.utils.UiUtils.fadeHtml; import static jadx.gui.utils.UiUtils.wrapHtml; public class JPackage extends JNode { private static final long serialVersionUID = -4120718634156839804L; public static final String PACKAGE_DEFAULT_HTML_STR = wrapHtml(fadeHtml(escapeHtml("<empty>"))); private final JavaPackage pkg; private final boolean enabled; private final List<JClass> classes; private final List<JPackage> subPackages; /** * Package created by full package alias, don't have a raw package reference. * `pkg` field point to the closest raw package leaf. */ private final boolean synthetic; private String name; /** * Should be called only from JNodeCache! */ public JPackage(JavaPackage pkg, boolean enabled, List<JClass> classes, List<JPackage> subPackages, boolean synthetic) { this.pkg = pkg; this.enabled = enabled; this.classes = classes; this.subPackages = subPackages; this.synthetic = synthetic; } public static JPackage makeTmpRoot() { return new JPackage(null, true, Collections.emptyList(), new ArrayList<>(), true); } public void update() { removeAllChildren(); if (isEnabled()) { for (JPackage pkg : subPackages) { pkg.update(); add(pkg); } for (JClass cls : classes) { cls.update(); add(cls); } } } @Override public JPopupMenu onTreePopupMenu(MainWindow mainWindow) { return new JPackagePopupMenu(mainWindow, this); } public JavaPackage getPkg() { return pkg; } public JavaNode getJavaNode() { return pkg; } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } public List<JPackage> getSubPackages() { return subPackages; } public List<JClass> getClasses() { return classes; } public boolean isEnabled() { return enabled; } public boolean isSynthetic() { return synthetic; } @Override public Icon getIcon() { return Icons.PACKAGE; } @Override public JClass getJParent() { return null; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } return pkg.equals(((JPackage) o).pkg); } @Override public int hashCode() { return pkg.hashCode(); } @Override public String makeString() { return name; } @Override public String makeStringHtml() { if (name.isEmpty()) { return PACKAGE_DEFAULT_HTML_STR; } return name; } @Override public boolean disableHtml() { if (name.isEmpty()) { // show PACKAGE_DEFAULT_HTML_STR for empty package return false; } return true; } @Override public String makeLongString() { return pkg.getFullName(); } @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-gui/src/main/java/jadx/gui/treemodel/JMethod.java
jadx-gui/src/main/java/jadx/gui/treemodel/JMethod.java
package jadx.gui.treemodel; import java.util.Comparator; import java.util.List; import java.util.Set; import javax.swing.Icon; import javax.swing.JPopupMenu; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.jetbrains.annotations.NotNull; import jadx.api.JavaMethod; import jadx.api.JavaNode; import jadx.api.data.ICodeRename; import jadx.api.data.impl.JadxCodeRename; import jadx.api.data.impl.JadxNodeRef; import jadx.api.metadata.ICodeNodeRef; import jadx.core.deobf.NameMapper; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.instructions.args.ArgType; import jadx.gui.ui.MainWindow; import jadx.gui.ui.cellrenders.MethodRenderHelper; import jadx.gui.ui.dialog.RenameDialog; import jadx.gui.utils.UiUtils; public class JMethod extends JNode implements JRenameNode { private static final long serialVersionUID = 3834526867464663751L; private final transient JavaMethod mth; private final transient JClass jParent; /** * Should be called only from JNodeCache! */ public JMethod(JavaMethod javaMethod, JClass jClass) { this.mth = javaMethod; this.jParent = jClass; } @Override public JavaNode getJavaNode() { return mth; } public JavaMethod getJavaMethod() { return mth; } @Override public ICodeNodeRef getCodeNodeRef() { return mth.getMethodNode(); } @Override public JClass getJParent() { return jParent; } public ArgType getReturnType() { return mth.getReturnType(); } @Override public JClass getRootClass() { return jParent.getRootClass(); } @Override public Icon getIcon() { return MethodRenderHelper.getIcon(mth); } @Override public String getSyntaxName() { return SyntaxConstants.SYNTAX_STYLE_JAVA; } @Override public JPopupMenu onTreePopupMenu(MainWindow mainWindow) { return RenameDialog.buildRenamePopup(mainWindow, this); } String makeBaseString() { return MethodRenderHelper.makeBaseString(mth); } @Override public String getName() { return mth.getName(); } @Override public String getTitle() { return makeLongStringHtml(); } @Override public boolean canRename() { if (mth.isClassInit()) { return false; } return !mth.getMethodNode().contains(AFlag.DONT_RENAME); } @Override public JRenameNode replace() { if (mth.isConstructor()) { // rename class instead constructor return jParent; } return this; } @Override public ICodeRename buildCodeRename(String newName, Set<ICodeRename> renames) { List<JavaMethod> relatedMethods = mth.getOverrideRelatedMethods(); if (!relatedMethods.isEmpty()) { for (JavaMethod relatedMethod : relatedMethods) { renames.remove(new JadxCodeRename(JadxNodeRef.forMth(relatedMethod), "")); } } return new JadxCodeRename(JadxNodeRef.forMth(mth), newName); } @Override public boolean isValidName(String newName) { return NameMapper.isValidIdentifier(newName); } @Override public void removeAlias() { mth.removeAlias(); } @Override public void addUpdateNodes(List<JavaNode> toUpdate) { toUpdate.add(mth); toUpdate.addAll(mth.getUseIn()); List<JavaMethod> overrideRelatedMethods = mth.getOverrideRelatedMethods(); toUpdate.addAll(overrideRelatedMethods); for (JavaMethod ovrdMth : overrideRelatedMethods) { toUpdate.addAll(ovrdMth.getUseIn()); } } @Override public void reload(MainWindow mainWindow) { mainWindow.reloadTreePreservingState(); } @Override public String makeString() { return UiUtils.typeFormat(makeBaseString(), getReturnType()); } @Override public String makeStringHtml() { return UiUtils.typeFormatHtml(makeBaseString(), getReturnType()); } @Override public String makeLongString() { String name = mth.getDeclaringClass().getFullName() + '.' + makeBaseString(); return UiUtils.typeFormat(name, getReturnType()); } @Override public String makeLongStringHtml() { String name = mth.getDeclaringClass().getFullName() + '.' + makeBaseString(); return UiUtils.typeFormatHtml(name, getReturnType()); } @Override public boolean disableHtml() { return false; } @Override public String makeDescString() { return UiUtils.typeStr(getReturnType()) + " " + makeBaseString(); } @Override public boolean hasDescString() { return false; } @Override public int getPos() { return mth.getDefPos(); } @Override public int hashCode() { return mth.hashCode(); } @Override public boolean equals(Object o) { return this == o || o instanceof JMethod && mth.equals(((JMethod) o).mth); } private static final Comparator<JMethod> COMPARATOR = Comparator .comparing(JMethod::getJParent) .thenComparing(jMethod -> jMethod.mth.getMethodNode().getMethodInfo().getShortId()) .thenComparingInt(JMethod::getPos); public int compareToMth(@NotNull JMethod other) { return COMPARATOR.compare(this, other); } @Override public int compareTo(@NotNull JNode other) { if (other instanceof JMethod) { return compareToMth(((JMethod) other)); } if (other instanceof JClass) { JClass cls = (JClass) other; int cmp = jParent.compareToCls(cls); if (cmp != 0) { return cmp; } return 1; } return super.compareTo(other); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/LineNumbersMode.java
jadx-gui/src/main/java/jadx/gui/settings/LineNumbersMode.java
package jadx.gui.settings; public enum LineNumbersMode { DISABLE, NORMAL, DEBUG, AUTO }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/WindowLocation.java
jadx-gui/src/main/java/jadx/gui/settings/WindowLocation.java
package jadx.gui.settings; import java.awt.Rectangle; public class WindowLocation { private String windowId; private Rectangle bounds; // Don't remove. Used in json serialization public WindowLocation() { } public WindowLocation(String windowId, Rectangle bounds) { this.windowId = windowId; this.bounds = bounds; } public String getWindowId() { return windowId; } public void setWindowId(String windowId) { this.windowId = windowId; } public Rectangle getBounds() { return bounds; } public void setBounds(Rectangle bounds) { this.bounds = bounds; } @Override public int hashCode() { return windowId.hashCode(); } @Override public final boolean equals(Object o) { if (o instanceof WindowLocation) { WindowLocation that = (WindowLocation) o; return windowId.equals(that.windowId) && bounds.equals(that.bounds); } return false; } @Override public String toString() { return "WindowLocation{" + "id='" + windowId + '\'' + ", x=" + bounds.getX() + ", y=" + bounds.getY() + ", width=" + bounds.getWidth() + ", height=" + bounds.getHeight() + '}'; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/JadxProject.java
jadx-gui/src/main/java/jadx/gui/settings/JadxProject.java
package jadx.gui.settings; import java.io.Reader; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.StringJoiner; import java.util.function.Consumer; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import jadx.api.JadxArgs; import jadx.api.data.ICodeComment; import jadx.api.data.ICodeRename; import jadx.api.data.IJavaCodeRef; import jadx.api.data.IJavaNodeRef; import jadx.api.data.impl.JadxCodeComment; import jadx.api.data.impl.JadxCodeData; import jadx.api.data.impl.JadxCodeRef; import jadx.api.data.impl.JadxCodeRename; import jadx.api.data.impl.JadxNodeRef; import jadx.api.plugins.utils.CommonFileUtils; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.files.FileUtils; import jadx.gui.cache.manager.CacheManager; import jadx.gui.settings.data.ProjectData; import jadx.gui.settings.data.SaveOptionEnum; import jadx.gui.settings.data.TabViewState; import jadx.gui.ui.MainWindow; import jadx.gui.ui.codearea.EditorViewState; import jadx.gui.utils.RelativePathTypeAdapter; import static jadx.core.utils.GsonUtils.defaultGsonBuilder; import static jadx.core.utils.GsonUtils.interfaceReplace; public class JadxProject { private static final Logger LOG = LoggerFactory.getLogger(JadxProject.class); public static final String PROJECT_EXTENSION = "jadx"; private static final int SEARCH_HISTORY_LIMIT = 30; private final transient MainWindow mainWindow; private transient String name = "New Project"; private transient @Nullable Path projectPath; private transient boolean initial = true; private transient boolean saved; private ProjectData data = new ProjectData(); public JadxProject(MainWindow mainWindow) { this.mainWindow = mainWindow; } public void fillJadxArgs(JadxArgs jadxArgs) { jadxArgs.setInputFiles(FileUtils.toFiles(getFilePaths())); if (jadxArgs.getUserRenamesMappingsPath() == null) { jadxArgs.setUserRenamesMappingsPath(getMappingsPath()); } jadxArgs.setCodeData(getCodeData()); jadxArgs.getPluginOptions().putAll(data.getPluginOptions()); } public @Nullable Path getWorkingDir() { if (projectPath != null) { return projectPath.toAbsolutePath().getParent(); } List<Path> files = data.getFiles(); if (!files.isEmpty()) { Path path = files.get(0); return path.toAbsolutePath().getParent(); } return null; } /** * @return null if project not saved */ public @Nullable Path getProjectPath() { return projectPath; } private void setProjectPath(@NotNull Path projectPath) { this.projectPath = projectPath; this.name = CommonFileUtils.removeFileExtension(projectPath.getFileName().toString()); changed(); } public List<Path> getFilePaths() { return data.getFiles(); } public void setFilePaths(List<Path> files) { if (files.equals(getFilePaths())) { return; } if (files.isEmpty()) { data.setFiles(files); name = ""; } else { Collections.sort(files); data.setFiles(files); StringJoiner joiner = new StringJoiner("_"); for (Path p : files) { Path fileNamePart = p.getFileName(); if (fileNamePart == null) { joiner.add(p.toString()); continue; } String fileName = fileNamePart.toString(); if (!fileName.endsWith(".jadx.kts")) { joiner.add(CommonFileUtils.removeFileExtension(fileName)); } } String joinedName = joiner.toString(); name = StringUtils.abbreviate(joinedName, 100); } changed(); } public void setTreeExpansions(List<String> list) { if (list.equals(data.getTreeExpansionsV2())) { return; } data.setTreeExpansionsV2(list); changed(); } public List<String> getTreeExpansions() { return data.getTreeExpansionsV2(); } public JadxCodeData getCodeData() { return data.getCodeData(); } public void setCodeData(JadxCodeData codeData) { data.setCodeData(codeData); changed(); } public void saveOpenTabs(List<EditorViewState> tabs) { List<TabViewState> tabStateList = tabs.stream() .map(TabStateViewAdapter::build) .filter(Objects::nonNull) .collect(Collectors.toList()); if (data.setOpenTabs(tabStateList)) { changed(); } } public List<EditorViewState> getOpenTabs(MainWindow mw) { return data.getOpenTabs().stream() .map(s -> TabStateViewAdapter.load(mw, s)) .filter(Objects::nonNull) .collect(Collectors.toList()); } public Path getMappingsPath() { return data.getMappingsPath(); } public void setMappingsPath(Path mappingsPath) { data.setMappingsPath(mappingsPath); changed(); } /** * Do not expose options map directly to be able to intercept changes */ public void updatePluginOptions(Consumer<Map<String, String>> update) { update.accept(data.getPluginOptions()); changed(); } public @Nullable String getPluginOption(String key) { return data.getPluginOptions().get(key); } private Path cacheDir; public Path getCacheDir() { if (cacheDir == null) { cacheDir = resolveCachePath(data.getCacheDir()); } return cacheDir; } public void resetCacheDir() { cacheDir = resolveCachePath(null); } private Path resolveCachePath(@Nullable String cacheDirStr) { CacheManager cacheManager = mainWindow.getCacheManager(); Path newCacheDir = cacheManager.getCacheDir(this, cacheDirStr); String newCacheStr = cacheManager.buildCacheDirStr(newCacheDir); if (!newCacheStr.equals(cacheDirStr)) { data.setCacheDir(newCacheStr); changed(); } return newCacheDir; } public boolean isEnableLiveReload() { return data.isEnableLiveReload(); } public void setEnableLiveReload(boolean newValue) { if (newValue != data.isEnableLiveReload()) { data.setEnableLiveReload(newValue); changed(); } } public List<String> getSearchHistory() { return data.getSearchHistory(); } public void addToSearchHistory(String str) { if (str == null || str.isEmpty()) { return; } List<String> list = data.getSearchHistory(); if (!list.isEmpty() && list.get(0).equals(str)) { return; } list.remove(str); list.add(0, str); if (list.size() > SEARCH_HISTORY_LIMIT) { list.remove(list.size() - 1); } data.setSearchHistory(list); changed(); } public void setSearchResourcesFilter(String searchResourcesFilter) { data.setSearchResourcesFilter(searchResourcesFilter); } public String getSearchResourcesFilter() { return data.getSearchResourcesFilter(); } public void setSearchResourcesSizeLimit(int searchResourcesSizeLimit) { data.setSearchResourcesSizeLimit(searchResourcesSizeLimit); } public int getSearchResourcesSizeLimit() { return data.getSearchResourcesSizeLimit(); } private void changed() { JadxSettings settings = mainWindow.getSettings(); if (settings != null && settings.getSaveOption() == SaveOptionEnum.ALWAYS) { save(); } else { saved = false; } initial = false; mainWindow.updateProject(this); } public String getName() { return name; } public boolean isSaveFileSelected() { return projectPath != null; } public boolean isSaved() { return saved; } public boolean isInitial() { return initial; } public void saveAs(Path path) { mainWindow.getCacheManager().projectPathUpdate(this, path); setProjectPath(path); save(); } public void save() { Path savePath = getProjectPath(); if (savePath != null) { Path basePath = savePath.toAbsolutePath().getParent(); try (Writer writer = Files.newBufferedWriter(savePath, StandardCharsets.UTF_8)) { buildGson(basePath).toJson(data, writer); saved = true; } catch (Exception e) { throw new RuntimeException("Error saving project", e); } } } public static JadxProject load(MainWindow mainWindow, Path path) { try { JadxProject project = new JadxProject(mainWindow); project.data = loadProjectData(path); project.saved = true; project.setProjectPath(path); return project; } catch (Exception e) { LOG.error("Error loading project", e); return null; } } public static ProjectData loadProjectData(Path path) { Path basePath = path.toAbsolutePath().getParent(); try (Reader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { return buildGson(basePath).fromJson(reader, ProjectData.class); } catch (Exception e) { throw new JadxRuntimeException("Failed to load project file: " + path, e); } } private static Gson buildGson(Path basePath) { return defaultGsonBuilder() .registerTypeHierarchyAdapter(Path.class, new RelativePathTypeAdapter(basePath)) .registerTypeAdapter(ICodeComment.class, interfaceReplace(JadxCodeComment.class)) .registerTypeAdapter(ICodeRename.class, interfaceReplace(JadxCodeRename.class)) .registerTypeAdapter(IJavaNodeRef.class, interfaceReplace(JadxNodeRef.class)) .registerTypeAdapter(IJavaCodeRef.class, interfaceReplace(JadxCodeRef.class)) .create(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/JadxConfigExcludeExport.java
jadx-gui/src/main/java/jadx/gui/settings/JadxConfigExcludeExport.java
package jadx.gui.settings; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation to mark fields excluded from config export/copy actions. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface JadxConfigExcludeExport { }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/TabStateViewAdapter.java
jadx-gui/src/main/java/jadx/gui/settings/TabStateViewAdapter.java
package jadx.gui.settings; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JavaClass; import jadx.gui.plugins.mappings.JInputMapping; import jadx.gui.settings.data.TabViewState; import jadx.gui.settings.data.ViewPoint; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JInputScript; import jadx.gui.treemodel.JNode; import jadx.gui.treemodel.JResource; import jadx.gui.ui.MainWindow; import jadx.gui.ui.codearea.EditorViewState; public class TabStateViewAdapter { private static final Logger LOG = LoggerFactory.getLogger(TabStateViewAdapter.class); @Nullable public static TabViewState build(EditorViewState viewState) { TabViewState tvs = new TabViewState(); if (!saveJNode(tvs, viewState.getNode())) { LOG.debug("Can't save view state: " + viewState); return null; } tvs.setSubPath(viewState.getSubPath()); tvs.setCaret(viewState.getCaretPos()); tvs.setView(new ViewPoint(viewState.getViewPoint())); tvs.setActive(viewState.isActive()); tvs.setPinned(viewState.isPinned()); tvs.setBookmarked(viewState.isBookmarked()); tvs.setHidden(viewState.isHidden()); tvs.setPreviewTab(viewState.isPreviewTab()); return tvs; } @Nullable public static EditorViewState load(MainWindow mw, TabViewState tvs) { try { JNode node = loadJNode(mw, tvs); if (node == null) { return null; } EditorViewState viewState = new EditorViewState(node, tvs.getSubPath(), tvs.getCaret(), tvs.getView().toPoint()); viewState.setActive(tvs.isActive()); viewState.setPinned(tvs.isPinned()); viewState.setBookmarked(tvs.isBookmarked()); viewState.setHidden(tvs.isHidden()); viewState.setPreviewTab(tvs.isPreviewTab()); return viewState; } catch (Exception e) { LOG.error("Failed to load tab state: {}", tvs, e); return null; } } @Nullable private static JNode loadJNode(MainWindow mw, TabViewState tvs) { switch (tvs.getType()) { case "class": JavaClass javaClass = mw.getWrapper().searchJavaClassByRawName(tvs.getTabPath()); if (javaClass != null) { return mw.getCacheObject().getNodeCache().makeFrom(javaClass); } break; case "resource": JResource tmpNode = new JResource(null, tvs.getTabPath(), JResource.JResType.FILE); return mw.getTreeRoot().searchNode(tmpNode); // equals method in JResource check only name case "script": return mw.getTreeRoot() .followStaticPath("JInputs", "JInputScripts") .searchNode(node -> node instanceof JInputScript && node.getName().equals(tvs.getTabPath())); case "mapping": return mw.getTreeRoot().followStaticPath("JInputs").searchNode(node -> node instanceof JInputMapping); } return null; } private static boolean saveJNode(TabViewState tvs, JNode node) { if (node instanceof JClass) { tvs.setType("class"); tvs.setTabPath(((JClass) node).getCls().getRawName()); return true; } if (node instanceof JResource) { tvs.setType("resource"); tvs.setTabPath(node.getName()); return true; } if (node instanceof JInputScript) { tvs.setType("script"); tvs.setTabPath(node.getName()); return true; } if (node instanceof JInputMapping) { tvs.setType("mapping"); return true; } return false; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/JadxGUIArgs.java
jadx-gui/src/main/java/jadx/gui/settings/JadxGUIArgs.java
package jadx.gui.settings; import com.beust.jcommander.Parameter; import jadx.cli.JadxCLIArgs; import jadx.cli.config.JadxConfigExclude; public class JadxGUIArgs extends JadxCLIArgs { @JadxConfigExclude @Parameter( names = { "-sc", "--select-class" }, description = "GUI: Open the selected class and show the decompiled code" ) private String cmdSelectClass = null; public String getCmdSelectClass() { return cmdSelectClass; } public void setCmdSelectClass(String cmdSelectClass) { this.cmdSelectClass = cmdSelectClass; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/JadxSettingsData.java
jadx-gui/src/main/java/jadx/gui/settings/JadxSettingsData.java
package jadx.gui.settings; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.JFrame; import org.jetbrains.annotations.Nullable; import com.google.gson.annotations.SerializedName; import jadx.cli.LogHelper; import jadx.gui.cache.code.CodeCacheMode; import jadx.gui.cache.usage.UsageCacheMode; import jadx.gui.settings.data.SaveOptionEnum; import jadx.gui.ui.action.ActionModel; import jadx.gui.ui.tab.dnd.TabDndGhostType; import jadx.gui.utils.LafManager; import jadx.gui.utils.LangLocale; import jadx.gui.utils.NLS; import jadx.gui.utils.shortcut.Shortcut; /** * Data class to hold all jadx-gui settings. * Also inherit all options from jadx-cli. * Serialized/deserialized as JSON in {@link jadx.cli.config.JadxConfigAdapter}. * Annotation {@link JadxConfigExcludeExport} used to exclude environment (files, window states) * fields from copy/export. */ public class JadxSettingsData extends JadxGUIArgs { public static final int CURRENT_SETTINGS_VERSION = 23; private static final Path USER_HOME = Paths.get(System.getProperty("user.home")); @JadxConfigExcludeExport private Path lastSaveProjectPath = USER_HOME; @JadxConfigExcludeExport private Path lastOpenFilePath = USER_HOME; @JadxConfigExcludeExport private Path lastSaveFilePath = USER_HOME; @JadxConfigExcludeExport private List<Path> recentProjects = new ArrayList<>(); @JadxConfigExcludeExport private Map<String, WindowLocation> windowPos = new HashMap<>(); @JadxConfigExcludeExport private int mainWindowExtendedState = JFrame.NORMAL; private boolean flattenPackage = false; private boolean checkForUpdates = true; private JadxUpdateChannel jadxUpdateChannel = JadxUpdateChannel.STABLE; private float uiZoom = 1.0f; private boolean applyUiZoomToFonts = true; private String uiFontStr = ""; @SerializedName(value = "codeFontStr", alternate = "fontStr") private String codeFontStr = ""; private String smaliFontStr = ""; private String editorTheme = ""; private String lafTheme = LafManager.INITIAL_THEME_NAME; private LangLocale langLocale = NLS.defaultLocale(); private boolean autoStartJobs = false; private String excludedPackages = ""; private SaveOptionEnum saveOption = SaveOptionEnum.ASK; private Map<ActionModel, Shortcut> shortcuts = new HashMap<>(); private boolean showHeapUsageBar = false; private boolean alwaysSelectOpened = false; private boolean enablePreviewTab = false; private boolean useAlternativeFileDialog = false; private boolean codeAreaLineWrap = false; private int searchResultsPerPage = 50; private boolean useAutoSearch = true; private boolean keepCommonDialogOpen = false; private boolean smaliAreaShowBytecode = false; private LineNumbersMode lineNumbersMode = LineNumbersMode.AUTO; private int mainWindowVerticalSplitterLoc = 300; private int debuggerStackFrameSplitterLoc = 300; private int debuggerVarTreeSplitterLoc = 700; private String adbDialogPath = ""; private String adbDialogHost = "localhost"; private String adbDialogPort = "5037"; private CodeCacheMode codeCacheMode = CodeCacheMode.DISK; private UsageCacheMode usageCacheMode = UsageCacheMode.DISK; /** * Cache dir option values: * null - default (system) * "." - at project dir * other - custom */ private @Nullable String cacheDir = null; private boolean jumpOnDoubleClick = true; private boolean disableTooltipOnHover = false; private XposedCodegenLanguage xposedCodegenLanguage = XposedCodegenLanguage.JAVA; private int treeWidth = 130; private boolean dockLogViewer = true; private boolean dockQuickTabs = false; private TabDndGhostType tabDndGhostType = TabDndGhostType.OUTLINE; private int settingsVersion = CURRENT_SETTINGS_VERSION; public JadxSettingsData() { this.logLevel = LogHelper.LogLevelEnum.INFO; } public String getAdbDialogHost() { return adbDialogHost; } public void setAdbDialogHost(String adbDialogHost) { this.adbDialogHost = adbDialogHost; } public String getAdbDialogPath() { return adbDialogPath; } public void setAdbDialogPath(String adbDialogPath) { this.adbDialogPath = adbDialogPath; } public String getAdbDialogPort() { return adbDialogPort; } public void setAdbDialogPort(String adbDialogPort) { this.adbDialogPort = adbDialogPort; } public boolean isAlwaysSelectOpened() { return alwaysSelectOpened; } public void setAlwaysSelectOpened(boolean alwaysSelectOpened) { this.alwaysSelectOpened = alwaysSelectOpened; } public boolean isAutoStartJobs() { return autoStartJobs; } public void setAutoStartJobs(boolean autoStartJobs) { this.autoStartJobs = autoStartJobs; } public @Nullable String getCacheDir() { return cacheDir; } public void setCacheDir(@Nullable String cacheDir) { this.cacheDir = cacheDir; } public boolean isCheckForUpdates() { return checkForUpdates; } public void setCheckForUpdates(boolean checkForUpdates) { this.checkForUpdates = checkForUpdates; } public boolean isCodeAreaLineWrap() { return codeAreaLineWrap; } public void setCodeAreaLineWrap(boolean codeAreaLineWrap) { this.codeAreaLineWrap = codeAreaLineWrap; } public CodeCacheMode getCodeCacheMode() { return codeCacheMode; } public void setCodeCacheMode(CodeCacheMode codeCacheMode) { this.codeCacheMode = codeCacheMode; } public int getDebuggerStackFrameSplitterLoc() { return debuggerStackFrameSplitterLoc; } public void setDebuggerStackFrameSplitterLoc(int debuggerStackFrameSplitterLoc) { this.debuggerStackFrameSplitterLoc = debuggerStackFrameSplitterLoc; } public int getDebuggerVarTreeSplitterLoc() { return debuggerVarTreeSplitterLoc; } public void setDebuggerVarTreeSplitterLoc(int debuggerVarTreeSplitterLoc) { this.debuggerVarTreeSplitterLoc = debuggerVarTreeSplitterLoc; } public boolean isDisableTooltipOnHover() { return disableTooltipOnHover; } public void setDisableTooltipOnHover(boolean disableTooltipOnHover) { this.disableTooltipOnHover = disableTooltipOnHover; } public boolean isDockLogViewer() { return dockLogViewer; } public void setDockLogViewer(boolean dockLogViewer) { this.dockLogViewer = dockLogViewer; } public boolean isDockQuickTabs() { return dockQuickTabs; } public void setDockQuickTabs(boolean dockQuickTabs) { this.dockQuickTabs = dockQuickTabs; } public String getEditorTheme() { return editorTheme; } public void setEditorTheme(String editorTheme) { this.editorTheme = editorTheme; } public boolean isEnablePreviewTab() { return enablePreviewTab; } public void setEnablePreviewTab(boolean enablePreviewTab) { this.enablePreviewTab = enablePreviewTab; } public String getExcludedPackages() { return excludedPackages; } public void setExcludedPackages(String excludedPackages) { this.excludedPackages = excludedPackages; } public boolean isFlattenPackage() { return flattenPackage; } public void setFlattenPackage(boolean flattenPackage) { this.flattenPackage = flattenPackage; } public JadxUpdateChannel getJadxUpdateChannel() { return jadxUpdateChannel; } public void setJadxUpdateChannel(JadxUpdateChannel jadxUpdateChannel) { this.jadxUpdateChannel = jadxUpdateChannel; } public boolean isJumpOnDoubleClick() { return jumpOnDoubleClick; } public void setJumpOnDoubleClick(boolean jumpOnDoubleClick) { this.jumpOnDoubleClick = jumpOnDoubleClick; } public boolean isKeepCommonDialogOpen() { return keepCommonDialogOpen; } public void setKeepCommonDialogOpen(boolean keepCommonDialogOpen) { this.keepCommonDialogOpen = keepCommonDialogOpen; } public String getLafTheme() { return lafTheme; } public void setLafTheme(String lafTheme) { this.lafTheme = lafTheme; } public LangLocale getLangLocale() { return langLocale; } public void setLangLocale(LangLocale langLocale) { this.langLocale = langLocale; } public Path getLastOpenFilePath() { return lastOpenFilePath; } public void setLastOpenFilePath(Path lastOpenFilePath) { this.lastOpenFilePath = lastOpenFilePath; } public Path getLastSaveFilePath() { return lastSaveFilePath; } public void setLastSaveFilePath(Path lastSaveFilePath) { this.lastSaveFilePath = lastSaveFilePath; } public Path getLastSaveProjectPath() { return lastSaveProjectPath; } public void setLastSaveProjectPath(Path lastSaveProjectPath) { this.lastSaveProjectPath = lastSaveProjectPath; } public LineNumbersMode getLineNumbersMode() { return lineNumbersMode; } public void setLineNumbersMode(LineNumbersMode lineNumbersMode) { this.lineNumbersMode = lineNumbersMode; } public int getMainWindowExtendedState() { return mainWindowExtendedState; } public void setMainWindowExtendedState(int mainWindowExtendedState) { this.mainWindowExtendedState = mainWindowExtendedState; } public int getMainWindowVerticalSplitterLoc() { return mainWindowVerticalSplitterLoc; } public void setMainWindowVerticalSplitterLoc(int mainWindowVerticalSplitterLoc) { this.mainWindowVerticalSplitterLoc = mainWindowVerticalSplitterLoc; } public List<Path> getRecentProjects() { return recentProjects; } public void setRecentProjects(List<Path> recentProjects) { this.recentProjects = recentProjects; } public SaveOptionEnum getSaveOption() { return saveOption; } public void setSaveOption(SaveOptionEnum saveOption) { this.saveOption = saveOption; } public int getSearchResultsPerPage() { return searchResultsPerPage; } public void setSearchResultsPerPage(int searchResultsPerPage) { this.searchResultsPerPage = searchResultsPerPage; } public int getSettingsVersion() { return settingsVersion; } public void setSettingsVersion(int settingsVersion) { this.settingsVersion = settingsVersion; } public Map<ActionModel, Shortcut> getShortcuts() { return shortcuts; } public void setShortcuts(Map<ActionModel, Shortcut> shortcuts) { this.shortcuts = shortcuts; } public boolean isShowHeapUsageBar() { return showHeapUsageBar; } public void setShowHeapUsageBar(boolean showHeapUsageBar) { this.showHeapUsageBar = showHeapUsageBar; } public boolean isSmaliAreaShowBytecode() { return smaliAreaShowBytecode; } public void setSmaliAreaShowBytecode(boolean smaliAreaShowBytecode) { this.smaliAreaShowBytecode = smaliAreaShowBytecode; } public String getUiFontStr() { return uiFontStr; } public void setUiFontStr(String uiFontStr) { this.uiFontStr = uiFontStr; } public String getCodeFontStr() { return codeFontStr; } public void setCodeFontStr(String codeFontStr) { this.codeFontStr = codeFontStr; } public String getSmaliFontStr() { return smaliFontStr; } public void setSmaliFontStr(String smaliFontStr) { this.smaliFontStr = smaliFontStr; } public TabDndGhostType getTabDndGhostType() { return tabDndGhostType; } public void setTabDndGhostType(TabDndGhostType tabDndGhostType) { this.tabDndGhostType = tabDndGhostType; } public int getTreeWidth() { return treeWidth; } public void setTreeWidth(int treeWidth) { this.treeWidth = treeWidth; } public float getUiZoom() { return uiZoom; } public void setUiZoom(float uiZoom) { this.uiZoom = uiZoom; } public boolean isApplyUiZoomToFonts() { return applyUiZoomToFonts; } public void setApplyUiZoomToFonts(boolean applyUiZoomToFonts) { this.applyUiZoomToFonts = applyUiZoomToFonts; } public UsageCacheMode getUsageCacheMode() { return usageCacheMode; } public void setUsageCacheMode(UsageCacheMode usageCacheMode) { this.usageCacheMode = usageCacheMode; } public boolean isUseAlternativeFileDialog() { return useAlternativeFileDialog; } public void setUseAlternativeFileDialog(boolean useAlternativeFileDialog) { this.useAlternativeFileDialog = useAlternativeFileDialog; } public boolean isUseAutoSearch() { return useAutoSearch; } public void setUseAutoSearch(boolean useAutoSearch) { this.useAutoSearch = useAutoSearch; } public Map<String, WindowLocation> getWindowPos() { return windowPos; } public void setWindowPos(Map<String, WindowLocation> windowPos) { this.windowPos = windowPos; } public XposedCodegenLanguage getXposedCodegenLanguage() { return xposedCodegenLanguage; } public void setXposedCodegenLanguage(XposedCodegenLanguage xposedCodegenLanguage) { this.xposedCodegenLanguage = xposedCodegenLanguage; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/JadxSettings.java
jadx-gui/src/main/java/jadx/gui/settings/JadxSettings.java
package jadx.gui.settings; import java.awt.Font; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; import java.awt.Window; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.JFrame; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import jadx.api.CommentsLevel; import jadx.api.DecompilationMode; import jadx.api.JadxArgs; import jadx.api.args.GeneratedRenamesMappingFileMode; import jadx.api.args.IntegerFormat; import jadx.api.args.ResourceNameSource; import jadx.api.args.UseSourceNameAsClassNameAlias; import jadx.api.args.UserRenamesMappingsMode; import jadx.cli.config.JadxConfigAdapter; import jadx.cli.config.JadxConfigExclude; import jadx.core.utils.GsonUtils; import jadx.gui.cache.code.CodeCacheMode; import jadx.gui.cache.usage.UsageCacheMode; import jadx.gui.settings.data.SaveOptionEnum; import jadx.gui.settings.data.ShortcutsWrapper; import jadx.gui.settings.font.FontSettings; import jadx.gui.ui.MainWindow; import jadx.gui.ui.tab.dnd.TabDndGhostType; import jadx.gui.utils.LangLocale; import jadx.gui.utils.PathTypeAdapter; import jadx.gui.utils.RectangleTypeAdapter; import static jadx.gui.settings.JadxSettingsData.CURRENT_SETTINGS_VERSION; public class JadxSettings { private static final Logger LOG = LoggerFactory.getLogger(JadxSettings.class); private static final int RECENT_PROJECTS_COUNT = 30; private final JadxConfigAdapter<JadxSettingsData> configAdapter; private final Object dataWriteSync = new Object(); private final ShortcutsWrapper shortcutsWrapper = new ShortcutsWrapper(); private final FontSettings fontSettings = new FontSettings(); private JadxSettingsData settingsData; public JadxSettings(JadxConfigAdapter<JadxSettingsData> configAdapter) { this.configAdapter = configAdapter; } public static JadxConfigAdapter<JadxSettingsData> buildConfigAdapter() { return new JadxConfigAdapter<>(JadxSettingsData.class, "gui", gsonBuilder -> { gsonBuilder.registerTypeHierarchyAdapter(Path.class, PathTypeAdapter.singleton()); gsonBuilder.registerTypeHierarchyAdapter(Rectangle.class, RectangleTypeAdapter.singleton()); }); } public String getSettingsJsonString() { return configAdapter.objectToJsonString(settingsData); } public void loadSettingsFromJsonString(String jsonStr) { loadSettingsData(configAdapter.jsonStringToObject(jsonStr)); } public void loadSettingsData(JadxSettingsData settingsData) { this.settingsData = settingsData; upgradeSettings(settingsData.getSettingsVersion()); fixOnLoad(); // update custom fields shortcutsWrapper.updateShortcuts(settingsData.getShortcuts()); fontSettings.bindData(settingsData); } private void upgradeSettings(int fromVersion) { if (settingsData.getSettingsVersion() == CURRENT_SETTINGS_VERSION) { return; } LOG.debug("upgrade settings from version: {} to {}", fromVersion, CURRENT_SETTINGS_VERSION); if (fromVersion <= 22) { fromVersion++; } if (fromVersion != CURRENT_SETTINGS_VERSION) { LOG.warn("Incorrect settings upgrade. Expected version: {}, got: {}", CURRENT_SETTINGS_VERSION, fromVersion); } settingsData.setSettingsVersion(CURRENT_SETTINGS_VERSION); sync(); } private void fixOnLoad() { if (settingsData.getThreadsCount() <= 0) { settingsData.setThreadsCount(JadxArgs.DEFAULT_THREADS_COUNT); } if (settingsData.getDeobfuscationMinLength() < 0) { settingsData.setDeobfuscationMinLength(0); } if (settingsData.getDeobfuscationMaxLength() < 0) { settingsData.setDeobfuscationMaxLength(0); } } public void sync() { synchronized (dataWriteSync) { configAdapter.save(settingsData); } } public String exportSettingsString() { Gson gson = GsonUtils.defaultGsonBuilder() .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getAnnotation(JadxConfigExclude.class) != null || f.getAnnotation(JadxConfigExcludeExport.class) != null; } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }) .create(); return gson.toJson(settingsData); } public JadxArgs toJadxArgs() { return settingsData.toJadxArgs(); } public List<String> getFiles() { return settingsData.getFiles(); } public String getCmdSelectClass() { return settingsData.getCmdSelectClass(); } public Path getLastOpenFilePath() { return settingsData.getLastOpenFilePath(); } public void setLastOpenFilePath(Path lastOpenFilePath) { settingsData.setLastOpenFilePath(lastOpenFilePath); } public Path getLastSaveProjectPath() { return settingsData.getLastSaveProjectPath(); } public void setLastSaveProjectPath(Path lastSaveProjectPath) { settingsData.setLastSaveProjectPath(lastSaveProjectPath); } public Path getLastSaveFilePath() { return settingsData.getLastSaveFilePath(); } public void setLastSaveFilePath(Path lastSaveFilePath) { settingsData.setLastSaveFilePath(lastSaveFilePath); } public boolean isFlattenPackage() { return settingsData.isFlattenPackage(); } public void setFlattenPackage(boolean flattenPackage) { settingsData.setFlattenPackage(flattenPackage); } public boolean isCheckForUpdates() { return settingsData.isCheckForUpdates(); } public void setCheckForUpdates(boolean checkForUpdates) { settingsData.setCheckForUpdates(checkForUpdates); sync(); } public boolean isDisableTooltipOnHover() { return settingsData.isDisableTooltipOnHover(); } public void setDisableTooltipOnHover(boolean disableTooltipOnHover) { settingsData.setDisableTooltipOnHover(disableTooltipOnHover); } public List<Path> getRecentProjects() { return Collections.unmodifiableList(settingsData.getRecentProjects()); } public void addRecentProject(@Nullable Path projectPath) { if (projectPath == null) { return; } List<Path> recentProjects = settingsData.getRecentProjects(); Path normPath = projectPath.toAbsolutePath().normalize(); recentProjects.remove(normPath); recentProjects.add(0, normPath); int count = recentProjects.size(); if (count > RECENT_PROJECTS_COUNT) { recentProjects.subList(RECENT_PROJECTS_COUNT, count).clear(); } } public void removeRecentProject(Path projectPath) { List<Path> recentProjects = settingsData.getRecentProjects(); recentProjects.remove(projectPath); } public void saveWindowPos(Window window) { synchronized (dataWriteSync) { WindowLocation pos = new WindowLocation(window.getClass().getSimpleName(), window.getBounds()); settingsData.getWindowPos().put(pos.getWindowId(), pos); } } public boolean loadWindowPos(Window window) { Map<String, WindowLocation> windowPos = settingsData.getWindowPos(); WindowLocation pos = windowPos.get(window.getClass().getSimpleName()); if (pos == null || pos.getBounds() == null) { return false; } if (!isAccessibleInAnyScreen(pos)) { return false; } window.setBounds(pos.getBounds()); if (window instanceof MainWindow) { ((JFrame) window).setExtendedState(getMainWindowExtendedState()); } return true; } private static boolean isAccessibleInAnyScreen(WindowLocation pos) { Rectangle windowBounds = pos.getBounds(); for (GraphicsDevice gd : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) { Rectangle screenBounds = gd.getDefaultConfiguration().getBounds(); if (screenBounds.intersects(windowBounds)) { return true; } } LOG.debug("Window saved position was ignored: {}", pos); return false; } public int getMainWindowExtendedState() { return settingsData.getMainWindowExtendedState(); } public void setMainWindowExtendedState(int mainWindowExtendedState) { settingsData.setMainWindowExtendedState(mainWindowExtendedState); } public boolean isShowHeapUsageBar() { return settingsData.isShowHeapUsageBar(); } public void setShowHeapUsageBar(boolean showHeapUsageBar) { settingsData.setShowHeapUsageBar(showHeapUsageBar); } public boolean isAlwaysSelectOpened() { return settingsData.isAlwaysSelectOpened(); } public void setAlwaysSelectOpened(boolean alwaysSelectOpened) { settingsData.setAlwaysSelectOpened(alwaysSelectOpened); } public boolean isEnablePreviewTab() { return settingsData.isEnablePreviewTab(); } public void setEnablePreviewTab(boolean enablePreviewTab) { settingsData.setEnablePreviewTab(enablePreviewTab); } public boolean isUseAlternativeFileDialog() { return settingsData.isUseAlternativeFileDialog(); } public void setUseAlternativeFileDialog(boolean useAlternativeFileDialog) { settingsData.setUseAlternativeFileDialog(useAlternativeFileDialog); } public String getExcludedPackages() { return settingsData.getExcludedPackages(); } public void setExcludedPackages(String excludedPackages) { settingsData.setExcludedPackages(excludedPackages); } public LangLocale getLangLocale() { return settingsData.getLangLocale(); } public void setLangLocale(LangLocale langLocale) { settingsData.setLangLocale(langLocale); } public boolean isAutoStartJobs() { return settingsData.isAutoStartJobs(); } public void setAutoStartJobs(boolean autoStartJobs) { settingsData.setAutoStartJobs(autoStartJobs); } public ShortcutsWrapper getShortcuts() { return shortcutsWrapper; } public int getTreeWidth() { return settingsData.getTreeWidth(); } public void setTreeWidth(int treeWidth) { settingsData.setTreeWidth(treeWidth); } public float getUiZoom() { return settingsData.getUiZoom(); } public void setUiZoom(float uiZoom) { settingsData.setUiZoom(uiZoom); fontSettings.applyUiZoom(uiZoom, isApplyUiZoomToFonts()); } public boolean isApplyUiZoomToFonts() { return settingsData.isApplyUiZoomToFonts(); } public void setApplyUiZoomToFonts(boolean applyUiZoomToFonts) { settingsData.setApplyUiZoomToFonts(applyUiZoomToFonts); fontSettings.applyUiZoom(getUiZoom(), applyUiZoomToFonts); } public FontSettings getFontSettings() { return fontSettings; } public Font getUiFont() { return fontSettings.getUiFontAdapter().getEffectiveFont(); } public void setUiFont(Font font) { fontSettings.getUiFontAdapter().setFont(font); } public Font getCodeFont() { return fontSettings.getCodeFontAdapter().getEffectiveFont(); } public void setCodeFont(Font font) { fontSettings.getCodeFontAdapter().setFont(font); } public Font getSmaliFont() { return fontSettings.getSmaliFontAdapter().getEffectiveFont(); } public void setSmaliFont(Font font) { fontSettings.getSmaliFontAdapter().setFont(font); } public String getEditorTheme() { return settingsData.getEditorTheme(); } public void setEditorTheme(String editorTheme) { settingsData.setEditorTheme(editorTheme); } public String getLafTheme() { return settingsData.getLafTheme(); } public void setLafTheme(String lafTheme) { settingsData.setLafTheme(lafTheme); } public boolean isCodeAreaLineWrap() { return settingsData.isCodeAreaLineWrap(); } public void setCodeAreaLineWrap(boolean lineWrap) { settingsData.setCodeAreaLineWrap(lineWrap); } public int getSearchResultsPerPage() { return settingsData.getSearchResultsPerPage(); } public void setSearchResultsPerPage(int searchResultsPerPage) { settingsData.setSearchResultsPerPage(searchResultsPerPage); } public boolean isUseAutoSearch() { return settingsData.isUseAutoSearch(); } public void saveUseAutoSearch(boolean useAutoSearch) { settingsData.setUseAutoSearch(useAutoSearch); sync(); } public void saveKeepCommonDialogOpen(boolean keepCommonDialogOpen) { settingsData.setKeepCommonDialogOpen(keepCommonDialogOpen); sync(); } public boolean isKeepCommonDialogOpen() { return settingsData.isKeepCommonDialogOpen(); } public int getMainWindowVerticalSplitterLoc() { return settingsData.getMainWindowVerticalSplitterLoc(); } public void setMainWindowVerticalSplitterLoc(int location) { settingsData.setMainWindowVerticalSplitterLoc(location); } public int getDebuggerStackFrameSplitterLoc() { return settingsData.getDebuggerStackFrameSplitterLoc(); } public void setDebuggerStackFrameSplitterLoc(int location) { settingsData.setDebuggerStackFrameSplitterLoc(location); } public int getDebuggerVarTreeSplitterLoc() { return settingsData.getDebuggerVarTreeSplitterLoc(); } public void setDebuggerVarTreeSplitterLoc(int location) { settingsData.setDebuggerVarTreeSplitterLoc(location); } public String getAdbDialogHost() { return settingsData.getAdbDialogHost(); } public void setAdbDialogHost(String adbDialogHost) { settingsData.setAdbDialogHost(adbDialogHost); } public String getAdbDialogPath() { return settingsData.getAdbDialogPath(); } public void setAdbDialogPath(String adbDialogPath) { settingsData.setAdbDialogPath(adbDialogPath); } public String getAdbDialogPort() { return settingsData.getAdbDialogPort(); } public void setAdbDialogPort(String adbDialogPort) { settingsData.setAdbDialogPort(adbDialogPort); } public CommentsLevel getCommentsLevel() { return settingsData.getCommentsLevel(); } public void setCommentsLevel(CommentsLevel level) { settingsData.setCommentsLevel(level); } public int getTypeUpdatesLimitCount() { return settingsData.getTypeUpdatesLimitCount(); } public void setTypeUpdatesLimitCount(int typeUpdatesLimitCount) { settingsData.setTypeUpdatesLimitCount(typeUpdatesLimitCount); } public LineNumbersMode getLineNumbersMode() { return settingsData.getLineNumbersMode(); } public void setLineNumbersMode(LineNumbersMode lineNumbersMode) { settingsData.setLineNumbersMode(lineNumbersMode); } public CodeCacheMode getCodeCacheMode() { return settingsData.getCodeCacheMode(); } public void setCodeCacheMode(CodeCacheMode codeCacheMode) { settingsData.setCodeCacheMode(codeCacheMode); } public UsageCacheMode getUsageCacheMode() { return settingsData.getUsageCacheMode(); } public void setUsageCacheMode(UsageCacheMode usageCacheMode) { settingsData.setUsageCacheMode(usageCacheMode); } public @Nullable String getCacheDir() { return settingsData.getCacheDir(); } public void setCacheDir(@Nullable String cacheDir) { settingsData.setCacheDir(cacheDir); } public boolean isJumpOnDoubleClick() { return settingsData.isJumpOnDoubleClick(); } public void setJumpOnDoubleClick(boolean jumpOnDoubleClick) { settingsData.setJumpOnDoubleClick(jumpOnDoubleClick); } public boolean isDockLogViewer() { return settingsData.isDockLogViewer(); } public void saveDockLogViewer(boolean dockLogViewer) { settingsData.setDockLogViewer(dockLogViewer); sync(); } public boolean isDockQuickTabs() { return settingsData.isDockQuickTabs(); } public void saveDockQuickTabs(boolean dockQuickTabs) { settingsData.setDockQuickTabs(dockQuickTabs); sync(); } public XposedCodegenLanguage getXposedCodegenLanguage() { return settingsData.getXposedCodegenLanguage(); } public void setXposedCodegenLanguage(XposedCodegenLanguage language) { settingsData.setXposedCodegenLanguage(language); } public JadxUpdateChannel getJadxUpdateChannel() { return settingsData.getJadxUpdateChannel(); } public void setJadxUpdateChannel(JadxUpdateChannel channel) { settingsData.setJadxUpdateChannel(channel); } public TabDndGhostType getTabDndGhostType() { return settingsData.getTabDndGhostType(); } public void setTabDndGhostType(TabDndGhostType tabDndGhostType) { settingsData.setTabDndGhostType(tabDndGhostType); } public boolean isRestoreSwitchOverString() { return settingsData.isRestoreSwitchOverString(); } public void setRestoreSwitchOverString(boolean restoreSwitchOverString) { settingsData.setRestoreSwitchOverString(restoreSwitchOverString); } public boolean isRenamePrintable() { return settingsData.isRenamePrintable(); } public UserRenamesMappingsMode getUserRenamesMappingsMode() { return settingsData.getUserRenamesMappingsMode(); } public void setUserRenamesMappingsMode(UserRenamesMappingsMode userRenamesMappingsMode) { settingsData.setUserRenamesMappingsMode(userRenamesMappingsMode); } public boolean isInlineAnonymousClasses() { return settingsData.isInlineAnonymousClasses(); } public void setInlineAnonymousClasses(boolean inlineAnonymousClasses) { settingsData.setInlineAnonymousClasses(inlineAnonymousClasses); } public boolean isRespectBytecodeAccessModifiers() { return settingsData.isRespectBytecodeAccessModifiers(); } public void setRespectBytecodeAccessModifiers(boolean respectBytecodeAccessModifiers) { settingsData.setRespectBytecodeAccessModifiers(respectBytecodeAccessModifiers); } public boolean isRenameCaseSensitive() { return settingsData.isRenameCaseSensitive(); } public DecompilationMode getDecompilationMode() { return settingsData.getDecompilationMode(); } public void setDecompilationMode(DecompilationMode decompilationMode) { settingsData.setDecompilationMode(decompilationMode); } public boolean isInlineMethods() { return settingsData.isInlineMethods(); } public void setInlineMethods(boolean inlineMethods) { settingsData.setInlineMethods(inlineMethods); } public boolean isFsCaseSensitive() { return settingsData.isFsCaseSensitive(); } public void setFsCaseSensitive(boolean fsCaseSensitive) { settingsData.setFsCaseSensitive(fsCaseSensitive); } public boolean isExtractFinally() { return settingsData.isExtractFinally(); } public void setExtractFinally(boolean extractFinally) { settingsData.setExtractFinally(extractFinally); } public int getSourceNameRepeatLimit() { return settingsData.getSourceNameRepeatLimit(); } public void setSourceNameRepeatLimit(int sourceNameRepeatLimit) { settingsData.setSourceNameRepeatLimit(sourceNameRepeatLimit); } public boolean isRenameValid() { return settingsData.isRenameValid(); } public boolean isSkipXmlPrettyPrint() { return settingsData.isSkipXmlPrettyPrint(); } public void setSkipXmlPrettyPrint(boolean skipXmlPrettyPrint) { settingsData.setSkipXmlPrettyPrint(skipXmlPrettyPrint); } public UseSourceNameAsClassNameAlias getUseSourceNameAsClassNameAlias() { return settingsData.getUseSourceNameAsClassNameAlias(); } public void setUseSourceNameAsClassNameAlias(UseSourceNameAsClassNameAlias useSourceNameAsClassNameAlias) { settingsData.setUseSourceNameAsClassNameAlias(useSourceNameAsClassNameAlias); } public boolean isShowInconsistentCode() { return settingsData.isShowInconsistentCode(); } public void setShowInconsistentCode(boolean showInconsistentCode) { settingsData.setShowInconsistentCode(showInconsistentCode); } public boolean isCfgOutput() { return settingsData.isCfgOutput(); } public void setCfgOutput(boolean cfgOutput) { settingsData.setCfgOutput(cfgOutput); } public boolean isEscapeUnicode() { return settingsData.isEscapeUnicode(); } public void setEscapeUnicode(boolean escapeUnicode) { settingsData.setEscapeUnicode(escapeUnicode); } public JadxArgs.UseKotlinMethodsForVarNames getUseKotlinMethodsForVarNames() { return settingsData.getUseKotlinMethodsForVarNames(); } public void setUseKotlinMethodsForVarNames(JadxArgs.UseKotlinMethodsForVarNames useKotlinMethodsForVarNames) { settingsData.setUseKotlinMethodsForVarNames(useKotlinMethodsForVarNames); } public String getDeobfuscationWhitelistStr() { return settingsData.getDeobfuscationWhitelistStr(); } public void setDeobfuscationWhitelistStr(String deobfuscationWhitelistStr) { settingsData.setDeobfuscationWhitelistStr(deobfuscationWhitelistStr); } public String getGeneratedRenamesMappingFile() { return settingsData.getGeneratedRenamesMappingFile(); } public boolean isRawCfgOutput() { return settingsData.isRawCfgOutput(); } public void setRawCfgOutput(boolean rawCfgOutput) { settingsData.setRawCfgOutput(rawCfgOutput); } public boolean isMoveInnerClasses() { return settingsData.isMoveInnerClasses(); } public void setMoveInnerClasses(boolean moveInnerClasses) { settingsData.setMoveInnerClasses(moveInnerClasses); } public boolean isUseDx() { return settingsData.isUseDx(); } public void setUseDx(boolean useDx) { settingsData.setUseDx(useDx); } public boolean isAddDebugLines() { return settingsData.isAddDebugLines(); } public boolean isUseHeadersForDetectResourceExtensions() { return settingsData.isUseHeadersForDetectResourceExtensions(); } public void setUseHeadersForDetectResourceExtensions(boolean useHeadersForDetectResourceExtensions) { settingsData.setUseHeadersForDetectResourceExtensions(useHeadersForDetectResourceExtensions); } public Map<String, String> getPluginOptions() { return settingsData.getPluginOptions(); } public boolean isDeobfuscationOn() { return settingsData.isDeobfuscationOn(); } public void setDeobfuscationOn(boolean deobfuscationOn) { settingsData.setDeobfuscationOn(deobfuscationOn); } public boolean isReplaceConsts() { return settingsData.isReplaceConsts(); } public void setReplaceConsts(boolean replaceConsts) { settingsData.setReplaceConsts(replaceConsts); } public boolean isAllowInlineKotlinLambda() { return settingsData.isAllowInlineKotlinLambda(); } public void setAllowInlineKotlinLambda(boolean allowInlineKotlinLambda) { settingsData.setAllowInlineKotlinLambda(allowInlineKotlinLambda); } public void setDeobfuscationUseSourceNameAsAlias(Boolean deobfuscationUseSourceNameAsAlias) { settingsData.setDeobfuscationUseSourceNameAsAlias(deobfuscationUseSourceNameAsAlias); } public void setRenameFlags(Set<JadxArgs.RenameEnum> renameFlags) { settingsData.setRenameFlags(renameFlags); } public void updateRenameFlag(JadxArgs.RenameEnum flag, boolean enabled) { if (enabled) { settingsData.getRenameFlags().add(flag); } else { settingsData.getRenameFlags().remove(flag); } } public void setUserRenamesMappingsPath(Path userRenamesMappingsPath) { settingsData.setUserRenamesMappingsPath(userRenamesMappingsPath); } public boolean isSkipSources() { return settingsData.isSkipSources(); } public boolean isDebugInfo() { return settingsData.isDebugInfo(); } public void setDebugInfo(boolean debugInfo) { settingsData.setDebugInfo(debugInfo); } public boolean isSkipResources() { return settingsData.isSkipResources(); } public void setSkipResources(boolean skipResources) { settingsData.setSkipResources(skipResources); } public ResourceNameSource getResourceNameSource() { return settingsData.getResourceNameSource(); } public void setResourceNameSource(ResourceNameSource resourceNameSource) { settingsData.setResourceNameSource(resourceNameSource); } public IntegerFormat getIntegerFormat() { return settingsData.getIntegerFormat(); } public void setIntegerFormat(IntegerFormat format) { settingsData.setIntegerFormat(format); } public boolean isFallbackMode() { return settingsData.isFallbackMode(); } public boolean isUseImports() { return settingsData.isUseImports(); } public void setUseImports(boolean useImports) { settingsData.setUseImports(useImports); } public int getDeobfuscationMinLength() { return settingsData.getDeobfuscationMinLength(); } public void setDeobfuscationMinLength(int deobfuscationMinLength) { settingsData.setDeobfuscationMinLength(deobfuscationMinLength); } public GeneratedRenamesMappingFileMode getGeneratedRenamesMappingFileMode() { return settingsData.getGeneratedRenamesMappingFileMode(); } public void setGeneratedRenamesMappingFileMode(GeneratedRenamesMappingFileMode generatedRenamesMappingFileMode) { settingsData.setGeneratedRenamesMappingFileMode(generatedRenamesMappingFileMode); } public int getDeobfuscationMaxLength() { return settingsData.getDeobfuscationMaxLength(); } public void setDeobfuscationMaxLength(int deobfuscationMaxLength) { settingsData.setDeobfuscationMaxLength(deobfuscationMaxLength); } public int getThreadsCount() { return settingsData.getThreadsCount(); } public void setThreadsCount(int threadsCount) { settingsData.setThreadsCount(threadsCount); } public SaveOptionEnum getSaveOption() { return settingsData.getSaveOption(); } public void setSaveOption(SaveOptionEnum saveOption) { settingsData.setSaveOption(saveOption); } public boolean isSmaliAreaShowBytecode() { return settingsData.isSmaliAreaShowBytecode(); } public void setSmaliAreaShowBytecode(boolean smaliAreaShowBytecode) { settingsData.setSmaliAreaShowBytecode(smaliAreaShowBytecode); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/JadxUpdateChannel.java
jadx-gui/src/main/java/jadx/gui/settings/JadxUpdateChannel.java
package jadx.gui.settings; public enum JadxUpdateChannel { STABLE, UNSTABLE, }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/XposedCodegenLanguage.java
jadx-gui/src/main/java/jadx/gui/settings/XposedCodegenLanguage.java
package jadx.gui.settings; public enum XposedCodegenLanguage { JAVA, KOTLIN, }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/font/FontSettings.java
jadx-gui/src/main/java/jadx/gui/settings/font/FontSettings.java
package jadx.gui.settings.font; import java.awt.Font; import javax.swing.UIManager; import com.formdev.flatlaf.FlatLaf; import com.formdev.flatlaf.fonts.inter.FlatInterFont; import com.formdev.flatlaf.fonts.jetbrains_mono.FlatJetBrainsMonoFont; import jadx.gui.settings.JadxSettingsData; import jadx.gui.utils.UiUtils; /** * Handle all font related settings */ public class FontSettings { static { FlatInterFont.install(); FlatJetBrainsMonoFont.install(); FlatLaf.setPreferredMonospacedFontFamily(FlatJetBrainsMonoFont.FAMILY); } private final FontAdapter uiFontAdapter; private final FontAdapter codeFontAdapter; private final FontAdapter smaliFontAdapter; private float uiZoom; private boolean applyUiZoomToFonts; public FontSettings() { int defFontSize = 13; Font defUiFont = new Font(FlatInterFont.FAMILY, Font.PLAIN, defFontSize); Font defCodeFont = new Font(FlatJetBrainsMonoFont.FAMILY, Font.PLAIN, defFontSize); uiFontAdapter = new FontAdapter(defUiFont); codeFontAdapter = new FontAdapter(defCodeFont); smaliFontAdapter = new FontAdapter(defCodeFont); } public void bindData(JadxSettingsData data) { uiFontAdapter.bindData(data.getUiFontStr(), data::setUiFontStr); codeFontAdapter.bindData(data.getCodeFontStr(), data::setCodeFontStr); smaliFontAdapter.bindData(data.getSmaliFontStr(), data::setSmaliFontStr); applyUiZoom(data.getUiZoom(), data.isApplyUiZoomToFonts()); } /** * Fetch and apply default font settings after FlatLaf init. */ public void updateDefaultFont() { Font defaultFont = UIManager.getFont("defaultFont"); if (defaultFont != null) { uiFontAdapter.setDefaultFont(defaultFont); } } public synchronized void applyUiZoom(float newUiZoom, boolean newApplyUiZoomToFonts) { if (UiUtils.nearlyEqual(uiZoom, newUiZoom) && applyUiZoomToFonts == newApplyUiZoomToFonts) { return; } uiZoom = newUiZoom; applyUiZoomToFonts = newApplyUiZoomToFonts; float effectiveFontZoom = newApplyUiZoomToFonts ? newUiZoom : 1.0f; uiFontAdapter.setUiZoom(effectiveFontZoom); codeFontAdapter.setUiZoom(effectiveFontZoom); smaliFontAdapter.setUiZoom(effectiveFontZoom); } public FontAdapter getUiFontAdapter() { return uiFontAdapter; } public FontAdapter getCodeFontAdapter() { return codeFontAdapter; } public FontAdapter getSmaliFontAdapter() { return smaliFontAdapter; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/font/FontAdapter.java
jadx-gui/src/main/java/jadx/gui/settings/font/FontAdapter.java
package jadx.gui.settings.font; import java.awt.Font; import java.util.Objects; import java.util.function.Consumer; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.utils.Utils; import jadx.gui.utils.FontUtils; import jadx.gui.utils.UiUtils; /** * Common handler for font updates and sync with settings data. */ public class FontAdapter { private static final Logger LOG = LoggerFactory.getLogger(FontAdapter.class); private Font defaultFont; private Font font; private Font effectiveFont; private Consumer<String> fontSetter; private float uiZoom; public FontAdapter(Font defaultFont) { Objects.requireNonNull(defaultFont); this.defaultFont = defaultFont; this.font = defaultFont; } /** * Load current font from data, and save font setter to future sync */ public void bindData(String fontStr, Consumer<String> fontStrSetter) { font = loadFromStr(fontStr); fontSetter = fontStrSetter; } public void setDefaultFont(Font newDefaultFont) { Objects.requireNonNull(newDefaultFont); Font prevDefaultFont = defaultFont; defaultFont = newDefaultFont; if (font == prevDefaultFont) { // font was set to default => update it also setFont(newDefaultFont); } } public Font getFont() { return font; } public Font getEffectiveFont() { return effectiveFont; } public void setFont(@Nullable Font newFont) { font = Utils.getOrElse(newFont, defaultFont); fontSetter.accept(getFontStr()); applyFontZoom(); } public void setUiZoom(float uiZoom) { this.uiZoom = uiZoom; applyFontZoom(); } private Font loadFromStr(String fontStr) { if (fontStr != null && !fontStr.isEmpty()) { try { return FontUtils.loadByStr(fontStr); } catch (Exception e) { LOG.warn("Failed to load font: {}, reset to default", fontStr, e); } } return defaultFont; } private String getFontStr() { if (font == defaultFont) { return ""; } return FontUtils.convertToStr(font); } private void applyFontZoom() { if (UiUtils.nearlyEqual(uiZoom, 1.0f)) { effectiveFont = font; } else { effectiveFont = font.deriveFont(font.getSize2D() * uiZoom); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/data/ViewPoint.java
jadx-gui/src/main/java/jadx/gui/settings/data/ViewPoint.java
package jadx.gui.settings.data; import java.awt.Point; public class ViewPoint { private int x; private int y; public ViewPoint() { this(0, 0); } public ViewPoint(Point p) { this(p.x, p.y); } public ViewPoint(int x, int y) { this.x = x; this.y = y; } public Point toPoint() { return new Point(x, y); } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } @Override public String toString() { return "ViewPoint{" + x + ", " + y + '}'; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false