Skip to content

Windows 上的安卓应用运行器:双击 APK 即装,应用以独立窗口与桌面图标运行,自持 QEMU 运行时

fix: 黑窗不再闪现、/data 自动初始化,冷启动 22 秒 / 快照 5 秒(v0.3.1)

RoutineMiku7b9bec9556af
diff --git a/README.md b/README.md
index 57581ea..cf9fdd0 100644
--- a/README.md
+++ b/README.md
@@ -121,7 +121,9 @@ ApkStart 是一个**自持**的项目,运行时组件全部由自己下载、
- **薄可写层**:单个 AVD 用差量用户数据 + 命名 quickboot 快照;关闭最后一个应用窗口后(空闲时)把内存状态存成快照,下次开机走恢复而不是冷启动。
- **空闲预热(默认开启)**:像 WSA / 应用宝电脑版一样,ApkStart 一启动就在后台把安卓环境引导好(窗口全程隐藏),点应用时只剩一次 `am start`;代价是空闲常驻约 1 GB 内存,设置里可关闭。
- **冷启动提速**:加速与引擎版本探测结果落盘缓存(按 exe 指纹失效)、跳过无谓的 `wmic` 进程枚举、开机探测改为自适应间隔(350ms 起)、guest 侧准备命令合并成一次 adb 往返;一次启动少等 5–10 秒。
-- 快照完整性校验:保存被打断留下的空壳(只有几十字节的 `snapshot.pb`)会被识别并清理,不再出现「加载失败 → 回退冷启动」的额外等待。
+- **`/data` 由 ApkStart 自己造**:官方系统镜像里的 `userdata.img` 只是 1 MB 全零占位,真正的格式化原本由 SDK 工具完成 —— 直接拉 `emulator.exe` 会跳过这一步,于是 `/data` 挂不上、guest 掉进 recovery 重启循环,表现就是「等好几分钟还是打不开」。现在首次启动会自己生成一份 4 KB block、带 `ENCRYPT`(文件级加密)与 `ext_attr`(SELinux 标签)的 ext4,并用自带的 `qemu-img` + `resize2fs` 撑到配置的容量。实测冷启动 ~23 秒、命中快照 ~10 秒。
+- 快照完整性校验:保存被打断留下的空壳(只有几十字节的 `snapshot.pb`)会被识别并清理;新版 emulator 写的是 `ram.bin`(老版本是 `ram.img`),两种命名都认,不会再把刚存好的 3 GB 快照误判成空壳删掉。
+- **命令窗口彻底不出现**:qemu 的控制台窗口属于 `conhost.exe`,pid 和 qemu 对不上,靠 pid 白名单一个都藏不住。现在改为「启动模拟器**之前**就打开压制 + 按窗口类名/标题兜底 + 开机 60 秒内 100ms 扫一次」,用户看不到任何黑框闪烁。
- **按需下载**:遇到仅含 ARM 原生库的应用才会补齐通用镜像;`.apks` / `.xapk` 拆分包自动用 `install-multiple` 安装。
- **可回收**:构建时裁掉非 x86_64 的 QEMU 目标(约 400 MB);设置页可清理旧镜像、旧快照、锁文件和遗留 AVD。
diff --git a/package.json b/package.json
index 16484c3..b399a35 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "apkstart",
"productName": "ApkStart",
- "version": "0.3.0",
+ "version": "0.3.1",
"description": "极致轻量的 Windows 安卓应用运行器:双击 APK 即装,应用以独立窗口与桌面图标运行",
"main": "src/main.js",
"author": "RoutineMiku",
diff --git a/src/core/agent.js b/src/core/agent.js
index cf9be7b..04835b7 100644
--- a/src/core/agent.js
+++ b/src/core/agent.js
@@ -167,9 +167,18 @@ class WinAgent extends EventEmitter {
* qemu 控制台子进程,Node 的 windowsHide 覆盖不到它;只能由窗口代理周期性
* 用 ShowWindow(SW_HIDE) 压住。启动即调用,boot 期间每帧都压一次,
* 避免任何闪现。失败(非 Windows / 代理不可用)时静默降级,不阻断启动。
+ *
+ * maxWaitMs:代理本身要现编译启动(几百毫秒,异常时可能十几秒)。调用点是在
+ * 「拉起模拟器之前」,绝不能因为代理起不来把开机拖住,所以这里给个硬上限。
+ * @param {number} maxWaitMs
*/
- async bootHide() {
- return this.call({ cmd: 'boothide', on: 1 }, 4000).catch(() => ({ ok: false }));
+ async bootHide(maxWaitMs = 3000) {
+ const call = this.call({ cmd: 'boothide', on: 1 }, 4000).catch(() => ({ ok: false }));
+ if (!maxWaitMs) return call;
+ return Promise.race([
+ call,
+ new Promise((resolve) => setTimeout(() => resolve({ ok: false, timeout: true }), maxWaitMs)),
+ ]);
}
/** 开机完成:停止隐藏,并让模拟器窗口显示出来(随后会被 embed 重新父化) */
diff --git a/src/core/emulator.js b/src/core/emulator.js
index 8e88289..e4517d4 100644
--- a/src/core/emulator.js
+++ b/src/core/emulator.js
@@ -10,12 +10,13 @@
*
* probe 回调由上层(Runtime)提供,用于判断 Android 是否真正就绪。
*/
-const { spawn, execFile } = require('child_process');
+const { spawn, spawnSync, execFile } = require('child_process');
const fs = require('fs');
const path = require('path');
const store = require('./store');
const { Provisioner } = require('./provision');
const doctor = require('./doctor');
+const userdata = require('./userdata');
const AVD_NAME = 'apkstart';
const SNAPSHOT_NAME = 'apkstart';
@@ -109,9 +110,13 @@ class EmulatorEngine {
hasSnapshot() {
const base = path.join(this.provisioner.paths().avdHome, `${AVD_NAME}.avd`, 'snapshots', SNAPSHOT_NAME);
const size = (p) => { try { return fs.statSync(p).size; } catch (_) { return 0; } };
- const ok = size(path.join(base, 'snapshot.pb')) > 1024
- && size(path.join(base, 'ram.img')) > 1024 * 1024;
- if (ok) return true;
+ const pb = size(path.join(base, 'snapshot.pb'));
+ // 新版 emulator(37.x)写的是 ram.bin,老版本写 ram.img。
+ // 只认 ram.img 的后果非常严重:刚存好的 3GB 快照会被当成空壳删掉,
+ // 于是每次都带 -no-snapshot-load,永远冷启动 —— 这是「打开很慢」的一半原因。
+ const ram = Math.max(size(path.join(base, 'ram.bin')), size(path.join(base, 'ram.img')));
+ if (pb > 1024 && ram > 1024 * 1024) return true;
+ if (pb === 0 && ram === 0) return false; // 目录本来就没有,别白删
try { fs.rmSync(base, { recursive: true, force: true }); } catch (_) { /* ignore */ }
this._cleanLegacySnapshots();
return false;
@@ -311,12 +316,92 @@ class EmulatorEngine {
].join('\n') + '\n';
fs.writeFileSync(cfgPath, cfg);
+ // /data 分区必须先「真的能用」,否则后面一切都是白等(见 ensureDataPartition 注释)
+ const data = this.ensureDataPartition(avdDir, dataMB);
+
return {
home, avdDir, ini: path.join(home, `${AVD_NAME}.ini`), image: choice,
- wipePending: this.wipePending, screen,
+ wipePending: this.wipePending, screen, data,
};
}
+ /**
+ * 保证 userdata 分区是一个**真正可用**的 ext4 —— 这是「点开应用 30 秒进桌面」的地基。
+ *
+ * 为什么必须自己做(三条都是实测踩出来的):
+ * 1. 系统镜像包里的 userdata.img 是 1MB 全零占位,真正格式化靠 avdmanager 调 SDK 的
+ * mke2fs。ApkStart 直接写 config.ini 拉 emulator,跳过那一步 → /data 全零 →
+ * 内核 "Invalid ext4 superblock on /dev/block/vdc" → guest 掉进 recovery 重启循环 →
+ * adbd 永远不上线 → 上层 probe 一直 pending,最后 240s 超时。原表现:点开要等好几分钟。
+ * 2. emulator 自带的 e2fsck/resize2fs 是 cygwin 版 e2fsprogs 1.42.12,**不认识 encrypt
+ * 特性**,带这个位它直接 exit 8 拒绝干活,所以「扩文件系统」必须排在补位之前。
+ * 3. 文件系统必须 ≥ 分区大小:只给 64MB 的话,APEX 解压 + dexopt 立刻写满,
+ * 之后所有 setxattr 返回 ENOSPC → SELinux 标签写不进去 → netd/media/tombstoned
+ * 一起 exit 1 → 开机卡在启动动画,adb 永远 offline。
+ */
+ ensureDataPartition(avdDir, dataMB = 4096) {
+ const emulatorExe = this.locate().emulatorExe;
+ if (!emulatorExe || !fs.existsSync(emulatorExe)) return { ok: false, reason: 'no-emulator' };
+ const emuDir = path.dirname(emulatorExe);
+ const img = path.join(avdDir, 'userdata-qemu.img');
+ const wantBytes = Math.max(1024, Math.round(dataMB || 4096)) * 1024 * 1024;
+ let size = 0;
+ try { size = fs.statSync(img).size; } catch (_) { /* 不存在 */ }
+
+ if (size > 0 && userdata.hasExt4Superblock(img)) {
+ if (size >= wantBytes) return { ok: true, created: false, size };
+ // 容量配置变大了:就地扩容(不重建,保留已装应用)
+ try {
+ userdata.clearEncryptFlag(img);
+ this._qemuImg('resize', img, wantBytes);
+ this._resize2fs(img);
+ userdata.setEncryptFlag(img);
+ return { ok: true, created: false, grown: true, size: wantBytes };
+ } catch (e) {
+ this.log(`扩容 userdata 失败(继续用现有分区):${e.message}`);
+ return { ok: true, created: false, size, error: e.message };
+ }
+ }
+
+ // 首次 / 旧版留下的全零占位 / 镜像损坏:全新造一个
+ try {
+ fs.rmSync(img, { force: true });
+ fs.rmSync(`${img}.qcow2`, { force: true });
+ // 先不带 encrypt 位(老 e2fsck/resize2fs 才肯干活)
+ fs.writeFileSync(img, userdata.buildEmptyExt4({ sizeMB: 64, encrypt: false }));
+ this._qemuImg('resize', img, wantBytes);
+ this._resize2fs(img);
+ userdata.setEncryptFlag(img);
+ this.log(`已重建 userdata:${(wantBytes / 1024 / 1024 / 1024).toFixed(1)}GB ext4(4K block,支持 FBE)`);
+ return { ok: true, created: true, size: wantBytes };
+ } catch (e) {
+ // 尽力而为:哪怕扩容失败,也要把 encrypt 位补回去,让 FBE 能初始化(分区会偏小)
+ try { userdata.setEncryptFlag(img); } catch (_) { /* ignore */ }
+ this.log(`重建 userdata 失败:${e.message}`);
+ return { ok: false, created: true, error: e.message };
+ }
+ }
+
+ /** emulator 自带 qemu-img.exe:把原始镜像文件撑到目标大小(稀疏,瞬间完成) */
+ _qemuImg(...args) {
+ const exe = path.join(path.dirname(this.locate().emulatorExe), 'qemu-img.exe');
+ const r = spawnSync(exe, ['-f', 'raw', ...args], {
+ cwd: path.dirname(exe), windowsHide: true, encoding: 'utf8',
+ });
+ if (r.status !== 0) throw new Error(`qemu-img ${args[0]} 失败: ${(r.stderr || '').trim() || r.status}`);
+ }
+
+ /** emulator 自带 resize2fs.exe(cygwin 版,必须在 bin64 目录下跑才能找到 DLL) */
+ _resize2fs(img) {
+ const bin = path.join(path.dirname(this.locate().emulatorExe), 'bin64');
+ const exe = path.join(bin, 'resize2fs.exe');
+ if (!fs.existsSync(exe)) throw new Error('缺少 resize2fs.exe');
+ const r = spawnSync(exe, [img], {
+ cwd: bin, windowsHide: true, encoding: 'utf8', timeout: 180000,
+ });
+ if (r.status !== 0) throw new Error(`resize2fs 失败: ${(r.stderr || '').trim() || r.status}`);
+ }
+
/** emulator 依赖这些环境变量定位 SDK / AVD;中文路径一律转 8.3 短路径 */
env(root, plan = {}) {
const safeRoot = doctor.shortPath(root);
@@ -373,8 +458,19 @@ class EmulatorEngine {
// qemu 会一直等一份不存在的内存状态,进程活着但永远不开机——
// 上层只看到「开机超时」,接着换参数重试,反而被 AVD 锁挡成
// "Running multiple emulators with the same AVD"。
- if (snapshot && !wipe && this.hasSnapshot()) args.push('-snapshot', SNAPSHOT_NAME);
- else args.push('-no-snapshot');
+ // 快照参数决定「下次开机是 8 秒还是 90 秒」,这里是第二个致命点:
+ // 老实现「没有快照就传 -no-snapshot」,而 -no-snapshot 同时禁掉了**退出时保存**,
+ // 于是第一次冷启动结束后永远产生不了快照,用户每次点开都是全量引导。
+ // 正确做法是 -no-snapshot-load:这次不加载(避免等一个不存在的快照),
+ // 但退出时照常把内存状态写成 apkstart,下次就直接恢复。
+ if (wipe) {
+ args.push('-no-snapshot');
+ } else if (snapshot !== false) {
+ args.push('-snapshot', SNAPSHOT_NAME);
+ if (!this.hasSnapshot()) args.push('-no-snapshot-load');
+ } else {
+ args.push('-no-snapshot');
+ }
if (wipe) args.push('-wipe-data');
if (accel === 'off') args.push('-accel', 'off');
return args;
@@ -478,18 +574,53 @@ class EmulatorEngine {
await this.killOrphanProcesses().catch(() => {});
}
- /** 清掉本专用端口上的 adb server(旧设备记录会把新模拟器挤成 offline) */
- _resetAdbServer(adbPort) {
- return new Promise((resolve) => {
- let adb = 'adb';
- try { adb = this.provisioner.adbVersionPath() || 'adb'; } catch (_) { /* 用 PATH 里的 */ }
+ /**
+ * 重建本专用端口上的 adb server。
+ *
+ * 这里是「打开应用要等两分钟」最主要的元凶,历史实现只 kill-server 就返回了:
+ * emulator 在启动瞬间会去连 ANDROID_ADB_SERVER_PORT 上的 adb daemon,
+ * 连不上就**再也不注册这台设备** —— adb devices 里要么没有 emulator-5554,
+ * 要么永远停在 offline(日志里就是那句 "Unable to connect to adb daemon on port: 5044")。
+ * 于是上层 probe 一直拿不到 sys.boot_completed,白等 3 分钟超时后重试,
+ * 每次重试都是全量冷启动,快照也因为「设备不在线」保存不了,形成死循环。
+ *
+ * 所以必须先 kill(清掉旧设备记录)再 start,并等到端口真的在监听才返回。
+ */
+ /** 供上层在 adb 传输卡住(offline / unauthorized)时主动重启一次 server */
+ async resetAdbServer() {
+ const port = Number(process.env.ANDROID_ADB_SERVER_PORT) || this.adbPort || 5044;
+ return this._resetAdbServer(port);
+ }
+
+ async _resetAdbServer(adbPort) {
+ let adb = 'adb';
+ try { adb = this.provisioner.adbVersionPath() || 'adb'; } catch (_) { /* 用 PATH 里的 */ }
+ const env = { ...process.env, ANDROID_ADB_SERVER_PORT: String(adbPort) };
+ const run = (args, timeout) => new Promise((resolve) => {
try {
- execFile(adb, ['kill-server'], {
- timeout: 6000, windowsHide: true,
- env: { ...process.env, ANDROID_ADB_SERVER_PORT: String(adbPort) },
- }, () => resolve());
+ execFile(adb, args, { timeout, windowsHide: true, env }, () => resolve());
} catch (_) { resolve(); }
});
+ await run(['kill-server'], 6000);
+ await run(['start-server'], 12000);
+ // adb start-server 在部分机器上同步返回得很快,但端口还没真正 listen,
+ // 这里等到能连上为止(最多 ~3 秒,正常几十毫秒)。
+ const net = require('net');
+ for (let i = 0; i < 25; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const alive = await new Promise((resolve) => {
+ const sock = net.connect({ host: '127.0.0.1', port: Number(adbPort) });
+ let done = false;
+ const fin = (v) => { if (done) return; done = true; try { sock.destroy(); } catch (_) { /* ignore */ } resolve(v); };
+ sock.setTimeout(150, () => fin(false));
+ sock.once('connect', () => fin(true));
+ sock.once('error', () => fin(false));
+ });
+ if (alive) return true;
+ // eslint-disable-next-line no-await-in-loop
+ await sleep(120);
+ }
+ return false;
}
/**
@@ -497,7 +628,7 @@ class EmulatorEngine {
* 参数错误/DLL 缺失时 emulator 通常 1 秒内就退;进程还在则立刻返回,
* 不必再干等固定 2.5 秒 —— 快照恢复时这段时间足够开机跑完一半。
*/
- _waitSpawnSettled(ms = 2200) {
+ _waitSpawnSettled(ms = 900) {
const proc = this.proc;
if (!proc) return Promise.resolve(true);
return new Promise((resolve) => {
@@ -559,6 +690,21 @@ class EmulatorEngine {
this.profile = profile;
const variants = doctor.planVariants(profile).slice(0, maxAttempts);
+ // 记住「上次拉起就崩」的 GPU 后端,下次把它排到最后。
+ // 实测:AMD Radeon 780M 上 `-gpu host` 能通过 emulator 自己的硬件检查,
+ // 但 VM 起来十几秒后进程直接 exit 1(日志里只有 "AEHD is operational"),
+ // 每次都要白等 20 多秒再退到 swangle。key 里带上 emulator 版本,
+ // 升级运行时后自动重新给它一次机会。
+ const badGpuKey = this.settings.engine.badGpu || '';
+ const [badVer, badGpu] = badGpuKey.includes('|') ? badGpuKey.split('|') : ['', ''];
+ if (badGpu && badVer === emuVersion) {
+ const rank = (v) => (v.gpu === badGpu ? 1 : 0);
+ variants.sort((a, b) => rank(a) - rank(b));
+ if (variants[0] && variants[0].gpu === badGpu && variants.length > 1) {
+ onLog(`上次 ${badGpu} 渲染后端启动即崩溃,本次改用 ${variants[1].gpu} 先试`);
+ }
+ }
+
const logFile = path.join(store.DATA_DIR, 'logs', 'emulator.log');
fs.mkdirSync(path.dirname(logFile), { recursive: true });
fs.appendFileSync(logFile, `\n\n=== ${new Date().toISOString()} START ${doctor.describeProfile(profile)} ===\n`);
@@ -588,6 +734,13 @@ class EmulatorEngine {
...plan,
wipe: plan.wipe || !!this.wipePending,
});
+ // 埋点:上层(main)用它在拉起模拟器**之前**打开黑窗压制。
+ // 控制台窗口在 spawn 之后几十毫秒就冒出来,事后再补一次扫描必然闪一下,
+ // 所以这里必须先把它打开、再拉起进程。
+ if (this.onBeforeSpawn) {
+ // eslint-disable-next-line no-await-in-loop
+ try { await this.onBeforeSpawn(); } catch (_) { /* ignore */ }
+ }
// eslint-disable-next-line no-await-in-loop
this.spawnOnce({ ...plan, wipe: plan.wipe || avd.wipePending }, { headless, onLog, logFile });
@@ -604,6 +757,7 @@ class EmulatorEngine {
try { this.provisioner.invalidateEnvCache(); } catch (_) { /* ignore */ }
}
onLog(`${d.title},自动换一组参数重试…`);
+ this._noteGpuFailure(plan);
continue;
}
@@ -616,10 +770,10 @@ class EmulatorEngine {
let ok = false;
let fatal = false;
let sawBooting = false;
- // 自适应探测间隔:快照恢复往往几秒内就能起,固定 3 秒一次意味着
- // 平均要多等 1.5 秒才「发现」它已经好了。这里从 350ms 起步逐步放宽到 1.5 秒,
- // 开机早期能立刻抓到,长引导过程也不会把 CPU 花在轮询上。
- let interval = 350;
+ // 快照恢复往往几秒内就能起,固定 3 秒一次意味着平均要多等 1.5 秒才「发现」
+ // 它已经好了。这里从 200ms 起步逐步放宽到 1.2 秒:开机早期能立刻抓到,
+ // 长引导过程也不会把 CPU 花在轮询上。
+ let interval = 200;
let lastNotice = 0;
// eslint-disable-next-line no-await-in-loop
while (Date.now() - started < timeout) {
@@ -650,7 +804,7 @@ class EmulatorEngine {
}
// eslint-disable-next-line no-await-in-loop
await sleep(interval);
- interval = Math.min(1500, Math.round(interval * 1.6));
+ interval = Math.min(1200, Math.round(interval * 1.6));
}
if (ok) {
@@ -671,6 +825,7 @@ class EmulatorEngine {
this.lastDiagnosis = d;
lastError = fatal ? `${d.title}:${d.hint}` : '开机超时(可能是首次引导较慢或硬件加速未生效)';
onLog(`${lastError},自动换一组参数重试…`);
+ this._noteGpuFailure(plan);
// eslint-disable-next-line no-await-in-loop
await this.killAttempt();
}
@@ -702,10 +857,11 @@ class EmulatorEngine {
*/
async saveSnapshotNow(adbPath, { timeout = 45000 } = {}) {
if (!adbPath) return false;
- return new Promise((resolve) => {
- execFile(adbPath, ['-s', this.serial, 'emu', 'avd', 'snapshot', 'save', SNAPSHOT_NAME],
- { timeout, windowsHide: true }, (err) => resolve(!err));
- });
+ const ok = await this._saveViaAdb(adbPath, { timeout });
+ // emulator 的 save 命令可能在写盘中途就回 OK,这里按文件完整性再确认一次,
+ // 只有 snapshot.pb 真正落盘才算数(否则下次加载会失败并白等几秒)。
+ if (!ok) return false;
+ return this.hasSnapshot();
}
/**
@@ -735,24 +891,30 @@ class EmulatorEngine {
/** 优雅停止:慢机器先保存 quickboot 快照,再走控制台关机,最后强杀进程树 */
async stop({ adbPath } = {}) {
- if (!this.proc) return true;
+ if (!this.proc) {
+ // 接管来的实例没有 proc 句柄,但端口上确实有机器在跑,不能直接返回 true 走人
+ if (!(await this._anyEmulatorPortAlive())) return true;
+ }
this.cancelSnapshotSave();
const serial = this.serial;
if (adbPath && this.snapshotWorthSaving !== false) {
// 关机前补存一次:空闲路径没来得及存(比如用户装完应用马上退出)时,
// 下一次开机仍然能走快照恢复,而不是重新冷启动。
- await new Promise((resolve) => {
- execFile(adbPath, ['-s', serial, 'emu', 'avd', 'snapshot', 'save', SNAPSHOT_NAME],
- { timeout: 20000, windowsHide: true }, () => resolve());
- });
+ // 3GB 内存写盘要几秒到二十几秒,超时给足,别让快照写一半就被 kill 掉。
+ await this._saveViaAdb(adbPath, { timeout: 60000 });
}
if (adbPath) {
await new Promise((resolve) => {
execFile(adbPath, ['-s', serial, 'emu', 'kill'],
- { timeout: 8000, windowsHide: true }, () => resolve());
+ { timeout: 10000, windowsHide: true }, () => resolve());
});
}
- for (let i = 0; i < 20 && this.proc; i += 1) {
+ // 等它自己走完「落盘 → 退出」的流程。以前固定等 6 秒就强杀,
+ // 正好把快照写盘掐断,留下一个只有 ram.img 没有 snapshot.pb 的空壳。
+ //
+ // 注意不能等 this.proc:emulator.exe 只是个启动器,spawn 完 qemu 自己就退了,
+ // 拿它的 exit 当「关机完成」会立刻进入强杀分支。这里以控制台端口为准。
+ for (let i = 0; i < 100 && (await this._consoleAlive()); i += 1) {
// eslint-disable-next-line no-await-in-loop
await sleep(300);
}
@@ -760,6 +922,43 @@ class EmulatorEngine {
return true;
}
+ /**
+ * 记下「拉起就崩」的 GPU 后端,下次启动把它排到最后。
+ * 只对 auto 模式生效:用户显式指定后端时尊重用户选择,不偷偷改。
+ */
+ _noteGpuFailure(plan) {
+ try {
+ const gpu = plan && plan.gpu;
+ if (!gpu) return;
+ // 软件渲染是兜底项,它已经是最慢/最稳的选择,没有更差的替代品可退
+ if (/software|swiftshader|swangle/.test(gpu)) return;
+ if ((this.settings.engine.gpuMode || 'auto') !== 'auto') return;
+ store.saveSettings({ engine: { badGpu: `${this._emuVersion || ''}|${gpu}` } });
+ } catch (_) { /* ignore */ }
+ }
+
+ /** 本实例的控制台端口(5554)上是否还有机器在跑 —— 判断「到底关干净了没有」 */
+ _consoleAlive() {
+ const net = require('net');
+ const port = this.port || 5554;
+ return new Promise((resolve) => {
+ const sock = net.connect({ host: '127.0.0.1', port });
+ let done = false;
+ const fin = (v) => { if (done) return; done = true; try { sock.destroy(); } catch (_) { /* ignore */ } resolve(v); };
+ sock.setTimeout(200, () => fin(false));
+ sock.once('connect', () => fin(true));
+ sock.once('error', () => fin(false));
+ });
+ }
+
+ /** 用 adb 触发一次快照保存(失败返回 false,调用方决定要不要再试) */
+ _saveViaAdb(adbPath, { timeout = 45000 } = {}) {
+ return new Promise((resolve) => {
+ execFile(adbPath, ['-s', this.serial, 'emu', 'avd', 'snapshot', 'save', SNAPSHOT_NAME],
+ { timeout, windowsHide: true }, (err) => resolve(!err));
+ });
+ }
+
recentLog(n = 40) { return this._log.slice(-n).map((x) => x.line); }
}
diff --git a/src/core/engine.js b/src/core/engine.js
index 2c32b52..9648da5 100644
--- a/src/core/engine.js
+++ b/src/core/engine.js
@@ -271,6 +271,9 @@ class Runtime {
// probe 交给 EmulatorEngine 的开机循环:进程退出/致命日志时它会换一组参数重试
// 每轮只发一次 adb 命令:以前是 get-state + getprop + pm path 三次进程拉起,
// 快照恢复时一轮就差 300~500ms,正好卡在「点开应用」的观感上。
+ let probeStart = Date.now();
+ let errStreak = 0;
+ let lastHeal = 0;
const probe = async ({ serial }) => {
if (!this.emulator.running()) return 'fatal';
if (!this._probeClient || this._probeClient.serial !== serial) {
@@ -282,9 +285,21 @@ class Runtime {
const lines = out.split(/\r?\n/).map((l) => l.trim());
const booted = lines[0] === '1' || /^1$/.test(lines[0] || '');
const pmReady = lines.some((l) => /^package:/.test(l));
+ errStreak = 0;
if (booted && pmReady) return 'ok';
return booted ? 'pending' : 'booting';
} catch (_) {
+ errStreak += 1;
+ // adb 传输会偶发地卡在 offline / unauthorized(另一个 adb server 抢了端口、
+ // 或者握手被打断),这时每一轮 shell 都报错,probe 永远 pending ——
+ // 上层只会看到「开机超时」,白白等到 240 秒。连错 6 轮就重启一次 server 自愈。
+ const now = Date.now();
+ if (errStreak >= 6 && now - probeStart > 25000 && now - lastHeal > 30000) {
+ lastHeal = now;
+ onLog('adb 连接异常,重启 adb server 后继续等待…');
+ await this.emulator.resetAdbServer().catch(() => {});
+ this._probeClient = null;
+ }
return 'pending';
}
};
@@ -504,16 +519,24 @@ class Runtime {
/** 优雅停止:emulator 走控制台关机,QEMU 走 monitor */
async stop({ graceful = true } = {}) {
+ const adbPath = this.adbPath();
if (this.emulator.running()) {
- await this.emulator.stop({ adbPath: this.adbPath() });
+ await this.emulator.stop({ adbPath });
return true;
}
// 接管来的模拟器(adoptExisting)在本进程里没有 proc 句柄,旧逻辑会直接
// return false —— 结果空闲看门狗永远关不掉它,容器一直占着 CPU/内存。
// 这条路径改用 adb 控制台关机,必要时再按端口强杀兜底。
+ //
+ // 注意:emulator.exe 只是个启动器,spawn 完 qemu 自己就退了,所以「自己拉起来的」
+ // 机器也常常落到这条分支。关机前必须补一次 saveSnapshotNow,否则快照永远存不下来,
+ // 用户每次点开都是全量冷启动(25 秒 vs 8 秒的差别就在这一步)。
let online = false;
try { online = await this.client().isOnline(); } catch (_) { /* ignore */ }
if (online && this.emuSerial) {
+ if (adbPath && this.emulator.snapshotWorthSaving !== false) {
+ await this.emulator.saveSnapshotNow(adbPath, { timeout: 60000 }).catch(() => false);
+ }
await this.client().exec(['emu', 'kill'], { timeout: 8000 }).catch(() => {});
for (let i = 0; i < 10; i += 1) {
// eslint-disable-next-line no-await-in-loop
@@ -992,17 +1015,15 @@ class Runtime {
if (this._watchdog) clearInterval(this._watchdog);
if (this._client && this._client.disposeInput) this._client.disposeInput();
this.emulator.cancelSnapshotSave();
- if (this.emulator.running()) {
- try { this.emulator.proc.kill(); } catch (_) { /* ignore */ }
- }
+ // 这里【绝对不能】强杀 qemu:
+ // 1) 强杀会把正在写盘的 quickboot 快照截断,只留下几 GB 的 ram.img 空壳,
+ // 下次开机加载失败 → 全量冷启动,这就是「每次打开都要等两分钟」的直接原因;
+ // 2) 留着它,下次打开 ApkStart 可以直接接管,点应用秒开(WSA / 应用宝电脑版同款行为)。
+ // 卸载时另走一条路(app:removeSelf 会显式清理进程)。
if (this.vmProc) {
try { this.vmProc.kill(); } catch (_) { /* ignore */ }
this.vmProc = null;
}
- // 退出时务必清掉 detached 的 qemu 进程:它独立于 ApkStart 存活(为了下次秒开),
- // 不在此强杀会一直锁住安装目录里的文件,导致卸载不干净、第三方粉碎工具也删不掉。
- // 仅在本进程真正退出时调用,不影响「关窗口→托盘常驻→下次秒开」的体验。
- this.emulator.killOrphanProcesses().catch(() => {});
}
get bootLog() { return this._bootLog.slice(-60); }
diff --git a/src/core/store.js b/src/core/store.js
index d327046..aa0669b 100644
--- a/src/core/store.js
+++ b/src/core/store.js
@@ -29,6 +29,9 @@ const DEFAULT_SETTINGS = {
// 带窗口的模拟器是原生 60fps + 原生鼠标键盘,ApkStart 只负责把它打扮成应用窗口。
headless: false,
gpuMode: 'auto', // auto = 按 emulator 版本自动挑后端并逐级降级
+ // 上次「拉起就崩」的渲染后端(格式 `<emulator版本>|<gpu>`);auto 模式下下次把它排到最后,
+ // 免得每次开机都先白等 20 多秒再退到软件渲染。升级运行时会自动失效。
+ badGpu: '',
forceTcg: false, // 保留给高级排障;正常路径已由 doctor 自动回退
audio: true, // 安卓应用的声音(提示音/视频)。关闭可省一点 CPU
// ---- 轻量容器(默认全开省资源,用户可逐项关掉)----
diff --git a/src/core/userdata.js b/src/core/userdata.js
new file mode 100644
index 0000000..5537925
--- /dev/null
+++ b/src/core/userdata.js
@@ -0,0 +1,227 @@
+'use strict';
+/**
+ * 生成一个最小但**合法**的 ext4 空镜像,供 Android Emulator 作为 userdata 种子。
+ *
+ * 为什么需要它(踩过的坑,别再重复):
+ * 1. 系统镜像包(system-images/.../userdata.img)里带的其实是一个 1MB 全零占位
+ * 文件,真正的格式化应该由 avdmanager 调 SDK 的 mke2fs 完成。ApkStart 是直接
+ * 写 config.ini 拉起 emulator 的,跳过了那一步 —— 于是 /data 一直是全零,
+ * 内核报 "Invalid ext4 superblock on /dev/block/vdc",guest 掉进
+ * recovery 重启循环,adbd 永远不上线。表现就是「点开应用等好几分钟最后失败」。
+ * (emulator 只带 e2fsck/resize2fs/tune2fs,**不带 mke2fs**,所以它自己也不会格式化。)
+ *
+ * 2. 块大小必须是 4096。Android 13 的 /data 走 metadata encryption,
+ * vold 会在 userdata 上叠一层 dm-default-key。该 dm 设备的逻辑块大小是
+ * 4096,而内核 sb_set_blocksize() 要求 fs block size >= 逻辑块大小,
+ * 用 1KB block 的镜像会得到 mount() = EINVAL,日志长得像这样:
+ * vold: [libfs_mgr] Cannot mount filesystem on /dev/block/dm-40 at /data: Invalid argument
+ * vold: fs_mgr_do_mount failed with rc -1
+ * 换成 4KB block 就正常了。
+ *
+ * 3. 必须带 EXT4_FEATURE_INCOMPAT_ENCRYPT(0x10000),否则 vold 的
+ * `cryptfs init_user0` 直接失败(exit 25)→ 又一次 recovery 重启。
+ *
+ * 镜像只有 64MB,emulator 启动时会自己 resize 到 AVD 配置的 dataPartition 大小,
+ * guest 里的 e2fsck/resize2fs 再把文件系统撑满,所以这里不需要大。
+ */
+
+const BLOCK = 4096;
+const INODE_SIZE = 128;
+const FIRST_INO = 11;
+
+// ext4 feature 位
+const COMPAT_EXT_ATTR = 0x8; // 没它 setxattr 直接 EOPNOTSUPP:SELinux 标签写不进去,
+ // netd / media / tombstoned 会一起 exit status 1
+const COMPAT_DIR_INDEX = 0x20;
+const INCOMPAT_FILETYPE = 0x2;
+const INCOMPAT_ENCRYPT = 0x10000;
+const RO_COMPAT_SPARSE_SUPER = 0x1;
+const RO_COMPAT_LARGE_FILE = 0x2;
+
+/**
+ * @param {{sizeMB?: number, encrypt?: boolean}} [opts]
+ * encrypt=false 时不带 ENCRYPT 位 —— 只用于「先让 emulator 自带的
+ * e2fsck/resize2fs(1.42.12,不认识 encrypt)先把文件系统扩到分区大小」,
+ * 之后再把这个位补回去。
+ * @returns {Buffer} 可直接写成 userdata 镜像的字节
+ */
+function buildEmptyExt4(opts = {}) {
+ const sizeMB = Math.max(8, Math.min(96, Math.round(opts.sizeMB || 64)));
+ const blocks = Math.floor((sizeMB * 1024 * 1024) / BLOCK);
+ // 单 block group:4KB block 时一组最多 8*4096 = 32768 块(128MB)
+ const blocksPerGroup = Math.min(blocks, 8 * BLOCK);
+
+ let inodes = Math.max(256, Math.round(blocks / 4));
+ inodes = Math.ceil(inodes / 8) * 8;
+ const inodeTableBlocks = Math.ceil((inodes * INODE_SIZE) / BLOCK);
+
+ const GD_BLOCK = 1;
+ const BB_BLOCK = 2;
+ const IB_BLOCK = 3;
+ const ITABLE_BLOCK = 4;
+ const DIR_BLOCK = ITABLE_BLOCK + inodeTableBlocks;
+ const usedBlocks = DIR_BLOCK + 1; // 已占用块数(0..DIR_BLOCK)
+
+ const buf = Buffer.alloc(blocks * BLOCK, 0);
+ const now = Math.floor(Date.now() / 1000);
+ const sb = 1024; // 超级块固定在 1024 偏移处
+
+ // ---------- superblock ----------
+ const reserved = Math.floor(blocks * 0.05);
+ buf.writeUInt32LE(inodes, sb + 0x00); // s_inodes_count
+ buf.writeUInt32LE(blocks, sb + 0x04); // s_blocks_count_lo
+ buf.writeUInt32LE(reserved, sb + 0x08); // s_r_blocks_count
+ buf.writeUInt32LE(blocks - usedBlocks, sb + 0x0C); // s_free_blocks_count
+ buf.writeUInt32LE(inodes - (FIRST_INO - 1), sb + 0x10); // s_free_inodes_count(要扣掉 1~10 号保留)
+ buf.writeUInt32LE(0, sb + 0x14); // s_first_data_block(4K 时为 0)
+ buf.writeUInt32LE(2, sb + 0x18); // s_log_block_size = 2 → 4096
+ buf.writeUInt32LE(2, sb + 0x1C); // s_log_cluster_size(必须等于 block size,否则 EINVAL)
+ buf.writeUInt32LE(blocksPerGroup, sb + 0x20); // s_blocks_per_group
+ buf.writeUInt32LE(blocksPerGroup, sb + 0x24); // s_clusters_per_group
+ buf.writeUInt32LE(inodes, sb + 0x28); // s_inodes_per_group
+ buf.writeUInt32LE(now, sb + 0x2C); // s_mtime
+ buf.writeUInt32LE(now, sb + 0x30); // s_wtime
+ buf.writeUInt16LE(0, sb + 0x34); // s_mnt_count
+ buf.writeUInt16LE(0xFFFF, sb + 0x36); // s_max_mnt_count
+ buf.writeUInt16LE(0xEF53, sb + 0x38); // magic
+ buf.writeUInt16LE(1, sb + 0x3A); // s_state = clean
+ buf.writeUInt16LE(1, sb + 0x3C); // s_errors = continue(千万别留 0)
+ buf.writeUInt16LE(0, sb + 0x3E); // s_minor_rev_level
+ buf.writeUInt32LE(now, sb + 0x40); // s_lastcheck
+ buf.writeUInt32LE(0, sb + 0x44); // s_checkinterval
+ buf.writeUInt32LE(0, sb + 0x48); // s_creator_os = Linux
+ buf.writeUInt32LE(1, sb + 0x4C); // s_rev_level = dynamic
+ buf.writeUInt16LE(0, sb + 0x50); // s_def_resuid
+ buf.writeUInt16LE(0, sb + 0x52); // s_def_resgid
+ buf.writeUInt32LE(FIRST_INO, sb + 0x54); // s_first_ino
+ buf.writeUInt16LE(INODE_SIZE, sb + 0x58); // s_inode_size
+ buf.writeUInt16LE(0, sb + 0x5A); // s_block_group_nr
+ buf.writeUInt32LE(COMPAT_EXT_ATTR | COMPAT_DIR_INDEX, sb + 0x5C); // s_feature_compat
+ buf.writeUInt32LE(INCOMPAT_FILETYPE | (opts.encrypt === false ? 0 : INCOMPAT_ENCRYPT), sb + 0x60); // s_feature_incompat
+ buf.writeUInt32LE(RO_COMPAT_SPARSE_SUPER | RO_COMPAT_LARGE_FILE, sb + 0x64);
+ Buffer.from('61706b7374617274303031', 'hex').copy(buf, sb + 0x68); // s_uuid
+ buf.write('data', sb + 0x78, 'ascii'); // s_volume_name
+ buf.write('/data', sb + 0x88, 'ascii'); // s_last_mounted
+ buf.writeUInt32LE(0, sb + 0xC8); // s_algorithm_usage_bitmap
+ buf.writeUInt8(0, sb + 0xCC + 1); // s_prealloc_blocks
+ buf.writeUInt8(0, sb + 0xCE);
+ // 支持的加密算法:1 = AES-256-XTS,2 = AES-256-CTS(Android 默认组合)
+ buf.writeUInt32LE(1, sb + 0x274);
+ buf.writeUInt32LE(2, sb + 0x278);
+ buf.writeUInt8(2, sb + 0xFC); // s_def_hash_version = half_md4
+ buf.writeUInt16LE(0, sb + 0xFE); // s_desc_size(非 64bit 用 0)
+
+ // ---------- group descriptor(block 1)----------
+ const gd = GD_BLOCK * BLOCK;
+ buf.writeUInt32LE(BB_BLOCK, gd + 0x00); // bg_block_bitmap
+ buf.writeUInt32LE(IB_BLOCK, gd + 0x04); // bg_inode_bitmap
+ buf.writeUInt32LE(ITABLE_BLOCK, gd + 0x08); // bg_inode_table
+ buf.writeUInt16LE(blocksPerGroup - usedBlocks, gd + 0x0C); // bg_free_blocks_count
+ buf.writeUInt16LE(inodes - FIRST_INO + 1, gd + 0x0E); // bg_free_inodes_count
+ buf.writeUInt16LE(1, gd + 0x10); // bg_used_dirs_count
+ buf.writeUInt16LE(0, gd + 0x12); // bg_flags
+
+ // ---------- block bitmap(block 2):bit i ↔ block i ----------
+ const bb = BB_BLOCK * BLOCK;
+ for (let blk = 0; blk < usedBlocks; blk += 1) {
+ buf[bb + (blk >> 3)] |= 1 << (blk & 7);
+ }
+ // 超出实际块数的 padding bit 必须置 1(位图按 blocks_per_group 铺满)
+ for (let bit = blocks; bit < blocksPerGroup; bit += 1) {
+ buf[bb + (bit >> 3)] |= 1 << (bit & 7);
+ }
+
+ // ---------- inode bitmap(block 3):1..10 预留给系统 ----------
+ const ib = IB_BLOCK * BLOCK;
+ for (let i = 0; i < FIRST_INO - 1; i += 1) {
+ buf[ib + (i >> 3)] |= 1 << (i & 7);
+ }
+
+ // ---------- root inode(inode 2)----------
+ const rootOff = ITABLE_BLOCK * BLOCK + (2 - 1) * INODE_SIZE;
+ buf.writeUInt16LE(0x41ED, rootOff + 0x00); // S_IFDIR | 0755
+ buf.writeUInt16LE(0, rootOff + 0x02); // i_uid
+ buf.writeUInt32LE(BLOCK, rootOff + 0x04); // i_size
+ buf.writeUInt32LE(now, rootOff + 0x08); // i_atime
+ buf.writeUInt32LE(now, rootOff + 0x0C); // i_ctime
+ buf.writeUInt32LE(now, rootOff + 0x10); // i_mtime
+ buf.writeUInt32LE(0, rootOff + 0x14); // i_dtime
+ buf.writeUInt16LE(0, rootOff + 0x18); // i_gid
+ buf.writeUInt16LE(2, rootOff + 0x1A); // i_links_count
+ buf.writeUInt32LE(BLOCK / 512, rootOff + 0x1C); // i_blocks(512B 单位)
+ buf.writeUInt32LE(0, rootOff + 0x20); // i_flags
+ buf.writeUInt32LE(DIR_BLOCK, rootOff + 0x28); // i_block[0](无 extents,走直接块)
+
+ // ---------- root 目录数据块 ----------
+ const dir = DIR_BLOCK * BLOCK;
+ buf.writeUInt32LE(2, dir + 0); // "." → inode 2
+ buf.writeUInt16LE(12, dir + 4);
+ buf.writeUInt8(1, dir + 6); // name_len
+ buf.writeUInt8(2, dir + 7); // file_type = DIR
+ buf.write('.', dir + 8, 'ascii');
+
+ buf.writeUInt32LE(2, dir + 12); // ".." → inode 2
+ buf.writeUInt16LE(BLOCK - 12, dir + 16);
+ buf.writeUInt8(2, dir + 18);
+ buf.writeUInt8(2, dir + 19);
+ buf.write('..', dir + 20, 'ascii');
+
+ return buf;
+}
+
+/** 判断一个镜像是否带合法 ext4 魔数(用于自愈:全零/损坏就重建) */
+function hasExt4Superblock(file) {
+ let fd;
+ try {
+ fd = require('fs').openSync(file, 'r');
+ const head = Buffer.alloc(2048);
+ const n = require('fs').readSync(fd, head, 0, 2048, 0);
+ if (n < 2048) return false;
+ return head.readUInt16LE(1024 + 0x38) === 0xEF53;
+ } catch (_) {
+ return false;
+ } finally {
+ if (fd !== undefined) {
+ try { require('fs').closeSync(fd); } catch (_) { /* ignore */ }
+ }
+ }
+}
+
+/**
+ * 把 ENCRYPT(fscrypt)特性位补回超级块。
+ * 顺序很重要:必须先让 emulator 自带的 resize2fs 把文件系统扩到分区大小,
+ * 再补这个位 —— 那套 cygwin 版 e2fsprogs 是 1.42.12,不认识 encrypt,
+ * 带着这个位 e2fsck/resize2fs 会直接拒绝执行。
+ */
+function setEncryptFlag(file) {
+ const fs = require('fs');
+ const fd = fs.openSync(file, 'r+');
+ try {
+ const b = Buffer.alloc(4);
+ const at = 1024 + 0x60; // s_feature_incompat
+ fs.readSync(fd, b, 0, 4, at);
+ b.writeUInt32LE(b.readUInt32LE(0) | INCOMPAT_ENCRYPT, 0);
+ fs.writeSync(fd, b, 0, 4, at);
+ } finally {
+ fs.closeSync(fd);
+ }
+}
+
+/** resize2fs 之前要把 ENCRYPT 位摘掉(老版本 e2fsprogs 不认识它会拒绝执行) */
+function clearEncryptFlag(file) {
+ const fs = require('fs');
+ const fd = fs.openSync(file, 'r+');
+ try {
+ const b = Buffer.alloc(4);
+ const at = 1024 + 0x60;
+ fs.readSync(fd, b, 0, 4, at);
+ b.writeUInt32LE(b.readUInt32LE(0) & ~INCOMPAT_ENCRYPT, 0);
+ fs.writeSync(fd, b, 0, 4, at);
+ } finally {
+ fs.closeSync(fd);
+ }
+}
+
+module.exports = {
+ buildEmptyExt4, hasExt4Superblock, setEncryptFlag, clearEncryptFlag, BLOCK,
+};
diff --git a/src/core/win/agent.ps1 b/src/core/win/agent.ps1
index 50884b6..1f95b31 100644
--- a/src/core/win/agent.ps1
+++ b/src/core/win/agent.ps1
@@ -1,4 +1,4 @@
-# ApkStart window agent (ASCII only).
+# ApkStart window agent (ASCII only).
# A single long-lived helper that owns every Win32 trick we need:
# * re-parents the Android emulator Qt window into an ApkStart BrowserWindow (one clean window,
# no emulator sidebar, no emulator title bar);
@@ -103,6 +103,10 @@ public class ApkAgent
// 开机隐藏:把模拟器主窗口 + 工具栏 + qemu 控制台黑窗一起压住,直到 embed 完成
static volatile bool _bootHide = false;
static long _bootHideSweep = 0;
+ // 兜底超时:万一 embed 没来(用户只是打开了 ApkStart 没点应用),
+ // 不能让 100ms 一轮的扫描永远跑下去白烧 CPU。每次真藏到窗口就续期。
+ static long _bootHideUntil = 0;
+ static long _bootHideStart = 0;
// Hook options. All three default to OFF: an "hook on" without options must
// never swallow anybody's clicks. JS sends the real config on every enable.
@@ -170,33 +174,112 @@ public class ApkAgent
// 开机阶段:把 qemu / emulator 的黑色控制台窗口藏起来,避免「命令窗口」闪现。
// 它们是 console 子系统进程,Node 的 windowsHide 覆盖不到子进程,只能靠 Win32 周期压住。
+ //
+ // 关键坑:Windows 10 以后控制台窗口真正属于 conhost.exe,GetWindowThreadProcessId
+ // 拿到的是 conhost 的 pid,不是 emulator 的 pid —— 老实现按 pid 白名单匹配,
+ // 于是这些黑窗一个都藏不住("点了没反应,先弹个 cmd 黑框"就是这么来的)。
+ // 现在改成「pid 命中 或 窗口标题命中(标题就是被启动的 exe 路径)」,两条路任一生效即隐藏。
static void HideConsoleWindows()
{
var pids = new System.Collections.Generic.HashSet<uint>();
try {
foreach (var p in Process.GetProcessesByName("qemu-system-x86_64")) pids.Add((uint)p.Id);
+ foreach (var p in Process.GetProcessesByName("qemu-system-x86_64-headless")) pids.Add((uint)p.Id);
foreach (var p in Process.GetProcessesByName("emulator")) pids.Add((uint)p.Id);
+ foreach (var p in Process.GetProcessesByName("emulator-headless")) pids.Add((uint)p.Id);
} catch { }
- if (pids.Count == 0) return;
EnumWindows(delegate(IntPtr h, IntPtr p)
{
+ if (!IsWindowVisible(h)) return true;
+ string cls = ClassOf(h);
+ bool isConsole = cls.IndexOf("ConsoleWindowClass", StringComparison.Ordinal) >= 0
+ || cls.IndexOf("CASCADIA_HOSTING_WINDOW_CLASS", StringComparison.Ordinal) >= 0;
+ if (!isConsole) return true; // 绝不动 Qt 画面窗口(QWindowIcon)
uint pid;
GetWindowThreadProcessId(h, out pid);
- if (!pids.Contains(pid)) return true;
- // 只藏控制台窗口(ConsoleWindowClass),绝不动 Qt 画面窗口(QWindowIcon)
- if (ClassOf(h).IndexOf("ConsoleWindowClass", StringComparison.Ordinal) >= 0)
- ShowWindow(h, 0);
+ string title = TitleOf(h);
+ bool ours = pids.Contains(pid)
+ || title.IndexOf("emulator", StringComparison.OrdinalIgnoreCase) >= 0
+ || title.IndexOf("qemu", StringComparison.OrdinalIgnoreCase) >= 0
+ || title.IndexOf("apkstart", StringComparison.OrdinalIgnoreCase) >= 0;
+ if (ours) ShowWindow(h, 0);
return true;
}, IntPtr.Zero);
}
+ // 诊断用:列出当前「可见」的控制台窗口(黑窗)及其归属,供 tools 里的验证脚本使用。
+ // ours=true 表示这就是 emulator/qemu 的控制台窗口。
+ static string ListConsoles()
+ {
+ var sb = new StringBuilder();
+ var pids = new System.Collections.Generic.HashSet<uint>();
+ try
+ {
+ foreach (var p in Process.GetProcessesByName("qemu-system-x86_64")) pids.Add((uint)p.Id);
+ foreach (var p in Process.GetProcessesByName("qemu-system-x86_64-headless")) pids.Add((uint)p.Id);
+ foreach (var p in Process.GetProcessesByName("emulator")) pids.Add((uint)p.Id);
+ }
+ catch { }
+ EnumWindows(delegate(IntPtr h, IntPtr p)
+ {
+ if (!IsWindowVisible(h)) return true;
+ string cls = ClassOf(h);
+ bool isConsole = cls.IndexOf("ConsoleWindowClass", StringComparison.Ordinal) >= 0
+ || cls.IndexOf("CASCADIA_HOSTING_WINDOW_CLASS", StringComparison.Ordinal) >= 0;
+ if (!isConsole) return true;
+ uint pid;
+ GetWindowThreadProcessId(h, out pid);
+ string title = TitleOf(h);
+ bool ours = pids.Contains(pid)
+ || title.IndexOf("emulator", StringComparison.OrdinalIgnoreCase) >= 0
+ || title.IndexOf("qemu", StringComparison.OrdinalIgnoreCase) >= 0;
+ if (sb.Length > 0) sb.Append(",");
+ sb.Append("{\"ours\":").Append(ours ? "true" : "false")
+ .Append(",\"pid\":").Append(pid)
+ .Append(",\"cls\":").Append(JsonStr(cls))
+ .Append(",\"title\":").Append(JsonStr(title))
+ .Append("}");
+ return true;
+ }, IntPtr.Zero);
+ return sb.ToString();
+ }
+
+ static string JsonStr(string s)
+ {
+ var b = new StringBuilder("\"");
+ foreach (char c in s == null ? "" : s)
+ {
+ if (c == '"' || c == '\\') b.Append('\\').Append(c);
+ else if (c >= ' ') b.Append(c);
+ }
+ b.Append("\"");
+ return b.ToString();
+ }
+
// 开机隐藏扫描:周期性把模拟器主窗口 + 工具栏 + 控制台黑窗一起压住
static void BootHideSweep()
{
IntPtr e = _emu != IntPtr.Zero ? _emu : FindEmulator();
+ bool sawProc = AnyEmulatorProcess();
if (e != IntPtr.Zero && IsWindowVisible(e)) ShowWindow(e, 0);
HideToolWindows();
HideConsoleWindows();
+ // 只要模拟器还在(启动中/待 embed),就持续压制;进程没了就不再续期,
+ // 由主循环的超时检查自动收工。
+ if (e != IntPtr.Zero || sawProc) _bootHideUntil = Environment.TickCount + 5000;
+ }
+
+ static bool AnyEmulatorProcess()
+ {
+ try
+ {
+ if (Process.GetProcessesByName("qemu-system-x86_64").Length > 0) return true;
+ if (Process.GetProcessesByName("qemu-system-x86_64-headless").Length > 0) return true;
+ if (Process.GetProcessesByName("emulator").Length > 0) return true;
+ if (Process.GetProcessesByName("emulator-headless").Length > 0) return true;
+ }
+ catch { }
+ return false;
}
// ------------------------------------------------------------------ embed / detach
@@ -539,12 +622,20 @@ public class ApkAgent
}
if (_embedAt != 0 && now - _embedAt >= 8000) _embedAt = 0;
- // 开机阶段周期性隐藏模拟器主窗 + 工具栏 + qemu 控制台黑窗,避免任何闪现
- if (_bootHide && now - _bootHideSweep > 300)
+ // 开机阶段周期性隐藏模拟器主窗 + 工具栏 + qemu 控制台黑窗,避免任何闪现。
+ // 前 60 秒用 100ms 一轮:控制台窗口从创建到可见只有几十毫秒,300ms 的间隔
+ // 足够让人眼看到一次黑框闪动。稳定之后放慢到 800ms,避免常驻空转。
+ long sweepGap = (now - _bootHideStart < 60000) ? 100 : 800;
+ if (_bootHide && now - _bootHideSweep > sweepGap)
{
_bootHideSweep = now;
BootHideSweep();
}
+ // 没人点应用、也没有进程需要藏了就自动收工,避免常驻空转
+ if (_bootHide && _bootHideUntil > 0 && now > _bootHideUntil)
+ {
+ _bootHide = false;
+ }
try
{
@@ -622,12 +713,18 @@ public class ApkAgent
if (e != IntPtr.Zero) GetWindowRect(e, out r);
Reply(sock, "{\"ok\":true,\"emu\":" + e.ToInt64() + ",\"w\":" + (r.R - r.L) + ",\"h\":" + (r.B - r.T) + "}");
}
+ else if (cmd == "consoles")
+ {
+ Reply(sock, "{\"ok\":true,\"list\":[" + ListConsoles() + "]}");
+ }
else if (cmd == "boothide")
{
if (L(line, "on") == 1)
{
_bootHide = true;
_bootHideSweep = 0;
+ _bootHideStart = Environment.TickCount;
+ _bootHideUntil = Environment.TickCount + 4000;
BootHideSweep();
}
else
diff --git a/src/main.js b/src/main.js
index 6a2e497..ce59c81 100644
--- a/src/main.js
+++ b/src/main.js
@@ -483,7 +483,8 @@ async function runLaunch(pkg) {
openAppWindow(pkg, '正在启动安卓运行时…');
// 开机阶段把模拟器主窗 + qemu 控制台黑窗藏起来,避免任何闪现(embed 完成后由
// appWin.embed() 调用 bootShow 解除隐藏)。失败(非 Windows/代理不可用)静默降级。
- if (winAgent) winAgent.bootHide().catch(() => {});
+ // 这里必须 await:不等压制生效就往下走,黑窗会在启动瞬间露出来。
+ if (winAgent) { try { await winAgent.bootHide(); } catch (_) { /* ignore */ } }
if (mainWindow && mainWindow.isVisible() && !IS_DEV) mainWindow.hide();
const r = await installer.launch(pkg, {
@@ -1158,6 +1159,9 @@ function registerIpc() {
return { ok: true, portable: true, dataDir: store.DATA_DIR, exeDir };
}
const { spawn } = require('child_process');
+ // 卸载前先收掉常驻的模拟器:qemu 会锁住 resources\runtime 里的 exe/dll,
+ // NSIS 删不掉就会留下半个安装目录。这里只针对「真的在卸载」,不影响日常退出。
+ try { await runtime?.emulator?.killOrphanProcesses(); } catch (_) { /* ignore */ }
// 先让本程序退出,再由一个独立进程延迟 2 秒拉起卸载器:
// 运行中的 exe 会锁住安装目录里的文件,直接拉起卸载器容易删不干净。
const cmd = `ping 127.0.0.1 -n 3 >nul & start "" "${uninstaller}"`;
@@ -1313,6 +1317,17 @@ if (!gotLock) {
};
attachAgentEvents(winAgent);
+ // 命令窗压制的「闸门」必须在模拟器进程创建之前打开。
+ // 旧实现是「等 ApkStart 起来 4 秒后再藏」,而模拟器在这之前就已经把
+ // qemu 控制台窗口创建出来了 —— 用户看到的就是一次一闪而过的黑框。
+ runtime.emulator.onBeforeSpawn = async () => {
+ if (!winAgent) return;
+ await winAgent.bootHide();
+ };
+ // 窗口代理是个 PowerShell 常驻进程,冷启动约 300~600ms。
+ // 提前拉起,别等到真正要藏窗口的那一刻才开始等。
+ winAgent.ensure().then(() => winAgent.bootHide()).catch(() => {});
+
registerIpc();
createWindow({ show: !parseArgs(process.argv).silent });
buildTray();
@@ -1340,6 +1355,8 @@ if (!gotLock) {
// 只有「已经装过应用 + 有可用运行时」才预热,避免第一次使用/纯管理场景白占内存。
const prewarmEnabled = store.getSettings().engine.prewarm !== false;
if (prewarmEnabled && !args.launch && store.getApps().length > 0) {
+ // 1.2 秒就够窗口画完第一帧了。以前等 4 秒,用户这时已经点了应用,
+ // 结果「点开」和「预热」抢同一个 AVD 锁,反而更慢。
setTimeout(async () => {
try {
const env = await runtime.provisioner.checkEnv();
@@ -1348,7 +1365,8 @@ if (!gotLock) {
return;
}
// 开机阶段把模拟器窗口与 qemu 控制台藏起来,用户不该看到任何窗
- if (winAgent) winAgent.bootHide().catch(() => {});
+ // 注意要 await:不等它生效就去 spawn,黑窗一定会露出来。
+ if (winAgent) { try { await winAgent.bootHide(); } catch (_) { /* ignore */ } }
const t0 = Date.now();
appLog('prewarm start');
const r = await runtime.prewarm({ onLog: (m) => appLog(`prewarm ${m}`) });
@@ -1358,7 +1376,7 @@ if (!gotLock) {
if (winAgent) winAgent.bootShow().catch(() => {});
}
} catch (e) { appLog(`prewarm error: ${e && e.message}`); /* 预热失败不影响后续正常打开 */ }
- }, 4000).unref?.();
+ }, 1200).unref?.();
} else {
appLog(`prewarm off (enabled=${prewarmEnabled} launch=${!!args.launch} apps=${store.getApps().length})`);
}
diff --git a/test/auto-test.js b/test/auto-test.js
index 38d9744..b56f4fa 100644
--- a/test/auto-test.js
+++ b/test/auto-test.js
@@ -281,8 +281,10 @@ const { AdbClient, friendlyInstallError, friendlyLaunchError } = require('../src
assert(!/swiftshader_indirect/.test(fresh));
assert(/-memory 2048/.test(fresh) && /-cores 2/.test(fresh));
if (!emu.hasSnapshot()) {
- assert(/-no-snapshot/.test(fresh), '没有快照时必须是 -no-snapshot');
- assert(!/-snapshot apkstart/.test(fresh), '没有快照时不能传 -snapshot');
+ // 没有快照时必须「只禁加载、不禁保存」:-no-snapshot 会连退出自动保存一起关掉,
+ // 那样第一次冷启动结束后永远产生不了快照,用户每次点开都是全量引导。
+ assert(/-no-snapshot-load/.test(fresh), '没有快照时应用 -no-snapshot-load(只跳过加载)');
+ assert(!/ -no-snapshot( |$)/.test(fresh), '没有快照时不能用 -no-snapshot(会禁掉退出保存)');
}
// 快照确实存在时才走 quickboot。注意要真的「像一个完整快照」:
// 保存中断会留下只有几十字节 snapshot.pb 的空壳,那种必须判定为没有快照,
@@ -296,7 +298,7 @@ const { AdbClient, friendlyInstallError, friendlyLaunchError } = require('../src
fs.writeFileSync(path.join(snapDir, 'apkstart', 'snapshot.pb'), 'x'.repeat(12));
assert(!emu.hasSnapshot(), '不完整的快照不能被当成可用快照');
const broken = emu.buildArgs({ gpu: 'software', memoryMB: 2048, cores: 2, snapshot: true }).join(' ');
- assert(/-no-snapshot/.test(broken) && !/-snapshot apkstart/.test(broken), '空壳快照必须回退冷启动');
+ assert(/-no-snapshot-load/.test(broken), '空壳快照必须回退冷启动(跳过加载)');
// 完整快照:pb 有内容 + ram.img 有数据(上一步的空壳会被 hasSnapshot 顺手清掉)
fs.mkdirSync(path.join(snapDir, 'apkstart'), { recursive: true });
@@ -304,14 +306,54 @@ const { AdbClient, friendlyInstallError, friendlyLaunchError } = require('../src
fs.writeFileSync(path.join(snapDir, 'apkstart', 'ram.img'), Buffer.alloc(2 * 1024 * 1024));
const withSnap = emu.buildArgs({ gpu: 'software', memoryMB: 2048, cores: 2, snapshot: true }).join(' ');
assert(/-snapshot apkstart/.test(withSnap), '有快照时应使用 quickboot 快照');
+ assert(!/-no-snapshot-load/.test(withSnap), '有完整快照时不该跳过加载');
if (created) fs.rmSync(snapDir, { recursive: true, force: true });
const cold = emu.buildArgs({ wipe: true }).join(' ');
- assert(/-wipe-data/.test(cold) && /-no-snapshot/.test(cold), 'wipe 时不能同时加载快照');
+ assert(/-wipe-data/.test(cold), 'wipe 时必须带 -wipe-data');
+ assert(/ -no-snapshot( |$)/.test(cold), 'wipe 时不能加载也不能保存快照');
});
- console.log('\n[显示 / 快捷方式 / 零操作]');
+ await test('新版 emulator 写的 ram.bin 必须被认作完整快照(否则刚存好的 3GB 会被当空壳删掉)', () => {
+ const { EmulatorEngine } = require('../src/core/emulator');
+ const emu = new EmulatorEngine(path.join(__dirname, '..'));
+ const avdDir = path.join(emu.provisioner.paths().avdHome, 'apkstart.avd');
+ const snapDir = path.join(avdDir, 'snapshots', 'apkstart');
+ fs.rmSync(path.join(avdDir, 'snapshots'), { recursive: true, force: true });
+ fs.mkdirSync(snapDir, { recursive: true });
+ fs.writeFileSync(path.join(snapDir, 'snapshot.pb'), 'x'.repeat(2048));
+ fs.writeFileSync(path.join(snapDir, 'ram.bin'), Buffer.alloc(2 * 1024 * 1024));
+ assert(emu.hasSnapshot(), 'ram.bin 应被认作完整快照');
+ const args = emu.buildArgs({ gpu: 'software', memoryMB: 2048, cores: 2, snapshot: true }).join(' ');
+ assert(/-snapshot apkstart/.test(args), '有快照时应走 quickboot');
+ assert(!/-no-snapshot-load/.test(args), '有完整快照时不该跳过加载');
+ fs.rmSync(path.join(avdDir, 'snapshots'), { recursive: true, force: true });
+ });
+
+ await test('userdata 种子镜像:4K block + ENCRYPT + 记账自洽', () => {
+ const { buildEmptyExt4 } = require('../src/core/userdata');
+ const sb = 1024;
+ const img = buildEmptyExt4({ sizeMB: 64, encrypt: false });
+ assert(img.readUInt16LE(sb + 0x38) === 0xEF53, 'superblock 魔数必须是 0xEF53');
+ // dm-default-key(Android 13 的 /data 元数据加密)逻辑块大小是 4096,
+ // fs block 小于它会让 mount() 返回 EINVAL —— 这是「挂不上 /data」的真凶。
+ assert(img.readUInt32LE(sb + 0x18) === 2, 's_log_block_size 必须是 2(4096 字节)');
+ assert(img.readUInt32LE(sb + 0x1C) === 2, 's_log_cluster_size 必须等于 block size');
+ // 没有 ext_attr 时 setxattr 返回 EOPNOTSUPP,SELinux 标签写不进去,
+ // netd / media / tombstoned 会一起 exit 1,开机卡在动画上。
+ assert((img.readUInt32LE(sb + 0x5C) & 0x8) !== 0, '必须带 ext_attr');
+ const total = img.readUInt32LE(sb + 0x04);
+ const free = img.readUInt32LE(sb + 0x0C);
+ const inodes = img.readUInt32LE(sb + 0x00);
+ const freeInodes = img.readUInt32LE(sb + 0x10);
+ assert(free > 0 && free < total, '空闲块数必须落在 (0, total) 之间');
+ assert(freeInodes === inodes - 10, '空闲 inode 必须扣掉 1~10 号保留(e2fsck 会核对)');
+ const withEnc = buildEmptyExt4({ sizeMB: 64 });
+ assert((withEnc.readUInt32LE(sb + 0x60) & 0x10000) !== 0, '默认必须带 ENCRYPT(FBE 必需)');
+ assert((img.readUInt32LE(sb + 0x60) & 0x10000) === 0, 'encrypt:false 时要能摘掉该位');
+ });
+ console.log('\n[显示 / 快捷方式 / 零操作]');
await test('窗口模式必须真的开窗口(否则应用进程活着但屏幕上看不见)', () => {
const { EmulatorEngine } = require('../src/core/emulator');
const emu = new EmulatorEngine(path.join(__dirname, '..'));
diff --git a/tools/check-agent.js b/tools/check-agent.js
new file mode 100644
index 0000000..3a92a99
--- /dev/null
+++ b/tools/check-agent.js
@@ -0,0 +1,24 @@
+'use strict';
+// 临时验证:窗口代理脚本能编译、能连上、boothide 能下发
+const { WinAgent } = require('../src/core/agent');
+
+(async () => {
+ const a = new WinAgent();
+ try {
+ await a.ensure();
+ console.log('agent ready, port=', a.port);
+ const r1 = await a.bootHide();
+ console.log('bootHide ->', JSON.stringify(r1));
+ await new Promise((r) => setTimeout(r, 500));
+ const r2 = await a.bootShow();
+ console.log('bootShow ->', JSON.stringify(r2));
+ const p = await a.probe();
+ console.log('probe ->', JSON.stringify(p));
+ } catch (e) {
+ console.error('FAILED:', e.message);
+ process.exitCode = 1;
+ } finally {
+ a.dispose();
+ setTimeout(() => process.exit(process.exitCode || 0), 300);
+ }
+})();
diff --git a/tools/check-console.js b/tools/check-console.js
new file mode 100644
index 0000000..c1d9aea
--- /dev/null
+++ b/tools/check-console.js
@@ -0,0 +1,79 @@
+'use strict';
+/**
+ * 黑窗验证:按主进程的方式拉起 emulator,检查「命令栏黑窗」是否被窗口代理压住。
+ *
+ * 只靠代码推断不可靠 —— 控制台窗口属于 conhost.exe,pid 和 emulator 完全对不上,
+ * 必须真的枚举一次可见窗口才算数。
+ *
+ * 用法: node tools/check-console.js [appRoot]
+ */
+const path = require('path');
+const { spawn } = require('child_process');
+const { WinAgent } = require('../src/core/agent');
+
+const INSTALL = process.argv[2] || path.join(process.env.LOCALAPPDATA || '', 'Programs', 'apkstart');
+const EMU = path.join(INSTALL, 'resources', 'runtime', 'emulator', 'emulator.exe');
+const AVD_HOME = path.join(process.env.APPDATA || '', 'apkstart', 'avd');
+const ROOT = path.join(INSTALL, 'resources', 'runtime');
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+(async () => {
+ const agent = new WinAgent();
+ await agent.ensure();
+ console.log('agent ready, port=', agent.port);
+
+ const list = async () => {
+ const r = await agent.call({ cmd: 'consoles' }, 4000);
+ return (r && r.list) || [];
+ };
+
+ const before = await list();
+ console.log('启动前可见控制台窗口:', JSON.stringify(before));
+
+ // 与主进程完全一致:detached + windowsHide + pipe
+ const proc = spawn(EMU, [
+ '-avd', 'apkstart', '-port', '5554', '-no-boot-anim', '-no-metrics',
+ '-crash-report-mode', 'disabled', '-gpu', 'swangle', '-memory', '3072',
+ '-cores', '3', '-no-skin', '-snapshot', 'apkstart',
+ ], {
+ cwd: path.dirname(EMU),
+ env: {
+ ...process.env,
+ ANDROID_SDK_ROOT: ROOT, ANDROID_HOME: ROOT,
+ ANDROID_AVD_HOME: AVD_HOME, ANDROID_EMULATOR_HOME: AVD_HOME,
+ ANDROID_ADB_SERVER_PORT: '5044',
+ },
+ windowsHide: true, detached: true, stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ proc.unref();
+
+ let sawConsole = 0;
+ for (let i = 0; i < 20; i += 1) {
+ await sleep(500);
+ const l = await list();
+ const ours = l.filter((w) => w.ours);
+ if (ours.length > sawConsole) {
+ sawConsole = ours.length;
+ console.log(`[${(i + 1) * 0.5}s] 出现黑窗:`, JSON.stringify(ours));
+ }
+ }
+ const afterSpawn = (await list()).filter((w) => w.ours);
+ console.log('未压制时仍在画面上的黑窗:', JSON.stringify(afterSpawn));
+
+ console.log('--- 打开 bootHide ---');
+ const r = await agent.bootHide();
+ console.log('bootHide:', JSON.stringify(r));
+ await sleep(1500);
+ const afterHide = (await list()).filter((w) => w.ours);
+ console.log('压制后剩余黑窗:', JSON.stringify(afterHide));
+
+ console.log('');
+ console.log(afterHide.length === 0
+ ? `结果:通过(启动过程中出现过 ${sawConsole} 个黑窗,压制后全部不可见)`
+ : '结果:失败(仍有可见黑窗)');
+
+ try { proc.kill(); } catch (_) { /* ignore */ }
+ agent.dispose();
+ process.exit(afterHide.length === 0 ? 0 : 1);
+})().catch((e) => { console.error('FATAL', e); process.exit(1); });
diff --git a/tools/e2e-boot.js b/tools/e2e-boot.js
new file mode 100644
index 0000000..b0295b8
--- /dev/null
+++ b/tools/e2e-boot.js
@@ -0,0 +1,36 @@
+'use strict';
+/**
+ * 端到端引导测速:直接驱动 Runtime,输出每个阶段耗时。
+ * 用法:node tools/e2e-boot.js <appRoot> [--stop|--keep]
+ * appRoot = 安装目录里的 resources/app(能找到 runtime/ 的那个)
+ */
+const path = require('path');
+const { Runtime } = require('../src/core/engine');
+
+const APP_ROOT = process.argv[2] || process.cwd();
+const mode = process.argv.includes('--stop') ? 'stop' : 'keep';
+
+(async () => {
+ const t0 = Date.now();
+ const rt = new Runtime(APP_ROOT);
+ const mark = (m) => console.log(`[${((Date.now() - t0) / 1000).toFixed(1)}s] ${m}`);
+
+ mark('prewarm begin');
+ const r = await rt.prewarm({ onLog: (m) => mark(m) });
+ mark(`prewarm result ok=${r && r.ok} bootMs=${r && r.bootMs} err=${(r && r.error) || ''}`);
+
+ if (r && r.ok) {
+ const c = rt.client();
+ const out = await c.shell('getprop sys.boot_completed; pm path android', { timeout: 15000 }).catch((e) => `ERR ${e.message}`);
+ mark(`after-ready probe: ${String(out).replace(/\n/g, ' | ')}`);
+ }
+
+ if (mode === 'stop') {
+ mark('stop begin (save snapshot)');
+ await rt.stop().catch((e) => mark(`stop err ${e.message}`));
+ mark('stop done');
+ const emu = rt.emulator;
+ mark(`hasSnapshot=${emu.hasSnapshot()}`);
+ }
+ process.exit(0);
+})().catch((e) => { console.error('FATAL', e); process.exit(1); });
diff --git a/tools/make-userdata.js b/tools/make-userdata.js
new file mode 100644
index 0000000..59d15d6
--- /dev/null
+++ b/tools/make-userdata.js
@@ -0,0 +1,17 @@
+'use strict';
+/**
+ * 生成 userdata 种子镜像(调试用)。
+ * 用法: node tools/make-userdata.js <输出文件> [大小MB]
+ */
+const fs = require('fs');
+const { buildEmptyExt4 } = require('../src/core/userdata');
+
+const out = process.argv[2];
+if (!out) {
+ console.error('用法: node tools/make-userdata.js <输出文件> [大小MB]');
+ process.exit(2);
+}
+const sizeMB = Number(process.argv[3] || 64);
+const img = buildEmptyExt4({ sizeMB });
+fs.writeFileSync(out, img);
+console.log(`已生成 ${out}(${(img.length / 1024 / 1024).toFixed(0)}MB,ext4/4KB block)`);