-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathpatch.js
More file actions
401 lines (347 loc) · 14.7 KB
/
patch.js
File metadata and controls
401 lines (347 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
import { exec, spawn, toast } from 'kernelsu-alt';
import { modDir, escapeShell } from '../index.js';
import { handleFileUpload, uploadFile } from './kpm.js';
import { getString } from '../language.js';
function uInt2String(ver) {
const val = typeof ver === 'string' ? parseInt(ver, 16) : ver;
const major = (val & 0xff0000) >> 16;
const minor = (val & 0x00ff00) >> 8;
const patch = (val & 0x0000ff);
return `${major}.${minor}.${patch}`;
}
function parseIni(str) {
const result = {};
let currentSection = null;
str.split('\n').forEach(line => {
line = line.trim();
if (!line || line.startsWith(';')) return;
if (line.startsWith('[') && line.endsWith(']')) {
currentSection = line.slice(1, -1);
result[currentSection] = {};
} else if (line.includes('=')) {
const parts = line.split('=');
const key = parts[0].trim();
const value = parts.slice(1).join('=').trim();
if (currentSection) {
result[currentSection][key] = value;
} else {
result[key] = value;
}
}
});
return result;
}
async function getInstalledVersion() {
if (import.meta.env.DEV) return uInt2String('c06');
const working = await exec(`kpatch hello`, { env: { PATH: `${modDir}/bin` } });
if (working.stdout.trim() === '') return null;
const version = await exec(`kpatch kpver`, { env: { PATH: `${modDir}/bin` } });
return uInt2String(version.stdout.trim());
}
let bootSlot = '';
let bootDev = '';
let kimgInfo = { banner: '', patched: false };
let kpimgInfo = { version: '', compile_time: '', config: '' };
let existedExtras = [];
let newExtras = [];
async function getKpimgInfo() {
if (kpimgInfo.version) {
document.getElementById('kpimg-version').textContent = getString('info_version', uInt2String(kpimgInfo.version));
document.getElementById('kpimg-time').textContent = getString('info_time', kpimgInfo.compile_time);
document.getElementById('kpimg-config').textContent = getString('info_config', kpimgInfo.config);
document.getElementById('kpimg').classList.remove('animate-hidden');
return;
}
const result = await exec(`kptools -l -k ${modDir}/bin/kpimg`, { env: { PATH: `${modDir}/bin` } });
if (import.meta.env.DEV) {
result.stdout = `[kpimg]\nversion=0xc06\ncompile_time=11:08:10 Dec 30 2025\nconfig=linux,release`;
}
const ini = parseIni(result.stdout);
if (ini.kpimg) {
kpimgInfo.version = ini.kpimg.version;
kpimgInfo.compile_time = ini.kpimg.compile_time;
kpimgInfo.config = ini.kpimg.config;
document.getElementById('kpimg-version').textContent = getString('info_version', uInt2String(ini.kpimg.version));
document.getElementById('kpimg-time').textContent = getString('info_time', ini.kpimg.compile_time);
document.getElementById('kpimg-config').textContent = getString('info_config', ini.kpimg.config);
}
document.getElementById('kpimg').classList.remove('animate-hidden');
}
function extractBootimg(bootDev) {
const child = spawn('magiskboot', ['unpack', bootDev], {
cwd: `${modDir}/tmp`,
env: { PATH: `${modDir}/bin:/data/adb/ksu/bin:/data/adb/magisk:$PATH` }
});
child.on('exit', () => {
parseBootimg();
});
}
async function parseBootimg() {
if (import.meta.env.DEV) {
document.getElementById('kernel-info').textContent = `6.18-Linux`;
document.getElementById('kernel').classList.remove('animate-hidden');
return;
}
let stdout = '', stderr = '';
const result = spawn('kptools', ['-l', '-i', 'kernel'], {
cwd: `${modDir}/tmp`,
env: { PATH: `${modDir}/bin:${modDir}/tmp:$PATH` }
});
result.stdout.on('data', (data) => stdout += data + '\n');
result.stderr.on('data', (data) => stderr += data);
const errno = await new Promise((resolve) => {
result.on('exit', (code) => resolve(code));
});
if (errno !== 0) {
toast(getString('msg_failed_parse_kernel', stderr));
return;
}
const ini = parseIni(stdout);
if (ini.kernel) {
kimgInfo.banner = ini.kernel.banner;
kimgInfo.patched = ini.kernel.patched === 'true';
// Kernel info card
document.getElementById('kernel-info').textContent = kimgInfo.banner;
document.getElementById('kernel').classList.remove('animate-hidden');
if (kimgInfo.patched && ini.kpimg) {
// Parse extras
existedExtras = [];
let kpmNum = parseInt(ini.kernel.extra_num);
if (isNaN(kpmNum) && ini.extras) {
kpmNum = parseInt(ini.extras.num);
}
if (kpmNum > 0) {
for (let i = 0; i < kpmNum; i++) {
const extra = ini[`extra ${i}`];
if (extra && extra.type.toUpperCase() === 'KPM') {
existedExtras.push({
type: 'KPM',
name: extra.name,
event: extra.event || 'pre-kernel-init',
args: extra.args || '',
version: extra.version,
license: extra.license,
author: extra.author,
description: extra.description,
isNew: false
});
}
}
}
}
renderKpmList();
}
}
async function extractAndParseBootimg() {
if (bootDev) {
document.getElementById('bootimg').classList.remove('animate-hidden');
extractBootimg(bootDev);
return;
}
// Prepare work directory
const prepare = spawn(`mkdir -p ${modDir}/tmp && rm -rf ${modDir}/tmp/* && cp ${modDir}/bin/kpimg ${modDir}/tmp/`);
await new Promise((resolve) => {
prepare.on('exit', () => resolve());
});
// get slot and device
const result = spawn('busybox', ['sh', `${modDir}/patch/boot_extract.sh`], {
env: { PATH: `${modDir}/bin:/data/adb/ksu/bin:/data/adb/magisk:$PATH`, ASH_STANDALONE: '1' }
});
result.stdout.on('data', (data) => {
if (data.match(/SLOT=(.*)/)) {
bootSlot = data.match(/SLOT=(.*)/)[1].trim();
} else if (data.match(/BOOTIMAGE=(.*)/)) {
bootDev = data.match(/BOOTIMAGE=(.*)/)[1].trim();
}
});
let stderr = '';
result.stderr.on('data', (data) => stderr += data);
const errno = await new Promise((resolve) => {
result.on('exit', (code) => resolve(code));
});
if (errno !== 0 && !import.meta.env.DEV) {
toast(getString('msg_boot_extract_failed'), stderr);
document.getElementById('bootimg-device').textContent = getString('msg_failed_locate_boot');
return;
}
// Bootimg info card
document.getElementById('bootimg-slot').textContent = bootSlot ? getString('info_slot', bootSlot) : '';
document.getElementById('bootimg-device').textContent = bootDev ? getString('info_device', bootDev) : getString('info_device_unknown');
document.getElementById('bootimg').classList.remove('animate-hidden');
if (bootDev || import.meta.env.DEV) {
extractBootimg(bootDev);
}
}
function renderKpmList() {
const list = document.getElementById('kpm-embed-list');
list.innerHTML = '';
const createCard = (item, index, isNew) => {
const card = document.createElement('div');
card.className = 'card module-card';
card.innerHTML = `
<div class="module-card-header">
<div class="flex-header">
<div class="module-card-title">${item.name}</div>
${isNew ? '' : '<div class="tag">' + getString('info_embedded') + '</div>'}
</div>
<div class="module-card-subtitle">${item.version}, ${getString('info_author', item.author || getString('msg_unknown'))}</div>
<div class="module-card-subtitle">${getString('info_args', item.args ? item.args : '(null)')}</div>
</div>
<div class="module-card-content">
<div class="module-card-text">${item.description || getString('info_no_description')}</div>
</div>
<md-divider></md-divider>
<div class="module-card-actions">
<md-filled-tonal-icon-button class="control">
<md-icon><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960"><path d="m370-80-16-128q-13-5-24.5-12T307-235l-119 50L78-375l103-78q-1-7-1-13.5v-27q0-6.5 1-13.5L78-585l110-190 119 50q11-8 23-15t24-12l16-128h220l16 128q13 5 24.5 12t22.5 15l119-50 110 190-103 78q1 7 1 13.5v27q0 6.5-2 13.5l103 78-110 190-118-50q-11 8-23 15t-24 12L590-80H370Zm70-80h79l14-106q31-8 57.5-23.5T639-327l99 41 39-68-86-65q5-14 7-29.5t2-31.5q0-16-2-31.5t-7-29.5l86-65-39-68-99 42q-22-23-48.5-38.5T533-694l-13-106h-79l-14 106q-31 8-57.5 23.5T321-633l-99-41-39 68 86 64q-5 15-7 30t-2 32q0 16 2 31t7 30l-86 65 39 68 99-42q22 23 48.5 38.5T427-266l13 106Zm42-180q58 0 99-41t41-99q0-58-41-99t-99-41q-59 0-99.5 41T342-480q0 58 40.5 99t99.5 41Zm-2-140Z" /></svg></md-icon>
</md-filled-tonal-icon-button>
<md-filled-tonal-icon-button class="unload">
<md-icon><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960"><path d="M280-120q-33 0-56.5-23.5T200-200v-520h-40v-80h200v-40h240v40h200v80h-40v520q0 33-23.5 56.5T680-120H280Zm400-600H280v520h400v-520ZM360-280h80v-360h-80v360Zm160 0h80v-360h-80v360ZM280-720v520-520Z"/></svg></md-icon>
</md-filled-tonal-icon-button>
</div>
`;
card.querySelector('.control').onclick = () => openOptionDialog(item);
card.querySelector('.unload').onclick = () => {
if (isNew) {
newExtras.splice(index, 1);
} else {
existedExtras.splice(index, 1);
}
renderKpmList();
};
return card;
};
const appendCard = (item, idx, isNew) => {
const card = createCard(item, idx, isNew);
list.appendChild(card);
}
existedExtras.forEach((item, idx) => appendCard(item, idx, false));
newExtras.forEach((item, idx) => appendCard(item, idx, true));
}
function openOptionDialog(item) {
const dialog = document.getElementById('kpm-option-dialog');
const eventSelect = document.getElementById('kpm-event-select');
const argsInput = document.getElementById('kpm-args-input');
eventSelect.value = item.event || 'pre-kernel-init';
argsInput.value = item.args || '';
const confirmBtn = dialog.querySelector('.confirm');
const newConfirm = confirmBtn.cloneNode(true);
confirmBtn.parentNode.replaceChild(newConfirm, confirmBtn);
newConfirm.onclick = () => {
item.event = eventSelect.value;
item.args = argsInput.value;
dialog.close();
renderKpmList();
};
const cancelBtn = dialog.querySelector('.cancel');
cancelBtn.onclick = () => dialog.close();
dialog.show();
}
async function embedKPM() {
const embedBtn = document.getElementById('embed');
const startBtn = document.getElementById('start');
handleFileUpload('.kpm', 'kpm-embed-list', async (file, onProgress, signal) => {
embedBtn.disabled = true;
startBtn.disabled = true;
// Generate random filename
const randName = Math.random().toString(36).substring(7) + '.kpm';
const tmpPath = `${modDir}/tmp/${randName}`;
try {
await uploadFile(file, tmpPath, onProgress, signal);
} catch (e) {
exec(`rm -f ${tmpPath}`);
throw e;
} finally {
embedBtn.disabled = false;
startBtn.disabled = false;
}
const result = await exec(`kptools -l -M "${randName}"`, {
cwd: `${modDir}/tmp`,
env: { PATH: `${modDir}/bin:$PATH` }
});
if (result.errno) {
toast(getString('msg_invalid_kpm_file'));
return;
}
const ini = parseIni(result.stdout);
if (ini.kpm) {
newExtras.push({
type: 'KPM',
name: ini.kpm.name,
event: 'pre-kernel-init', // default
args: '',
version: ini.kpm.version,
license: ini.kpm.license,
author: ini.kpm.author,
description: ini.kpm.description,
fileName: randName,
isNew: true
});
renderKpmList();
} else {
toast(getString('msg_could_not_parse_kpm'));
}
});
}
function patch(type) {
const terminal = document.querySelector('#patch-terminal');
const pageContent = terminal.closest('.page-content');
const flashToDevice = document.getElementById('flash-to-device');
const onOutput = (data) => {
terminal.innerHTML += `<div>${data}</div>`;
pageContent.scrollTo({ top: pageContent.scrollHeight, behavior: 'smooth' });
};
if (!bootDev) {
terminal.textContent = getString('msg_error_no_boot_image');
return;
}
let args = ['sh'];
if (type === "patch") {
args.push(
`${modDir}/patch/boot_patch.sh`,
bootDev,
flashToDevice.selected ? 'true' : 'false'
);
// New kpm
newExtras.forEach(extra => {
args.push('-M', `${modDir}/tmp/${extra.fileName}`);
if (extra.args) args.push('-A', escapeShell(extra.args));
if (extra.event) args.push('-V', extra.event);
args.push('-T', 'kpm');
});
// Embeded kpm
existedExtras.forEach(extra => {
args.push('-E', extra.name);
if (extra.args) args.push('-A', escapeShell(extra.args));
if (extra.event) args.push('-V', extra.event);
args.push('-T', 'kpm');
});
} else {
// Unpatch logic
args.push(`${modDir}/patch/boot_unpatch.sh`, bootDev);
}
const process = spawn(
`busybox`,
args,
{
cwd: `${modDir}/tmp`,
env: {
PATH: `${modDir}/bin:/data/adb/ksu/bin:/data/adb/magisk:$PATH`,
ASH_STANDALONE: '1'
}
}
);
process.stdout.on('data', onOutput);
process.stderr.on('data', onOutput);
process.on('exit', (code) => {
if (code === 0) {
document.getElementById('reboot-fab').classList.remove('hide');
bootSlot = '';
bootDev = '';
kimgInfo = { banner: '', patched: false };
newExtras = [];
}
exec(`rm -rf ${modDir}/tmp`);
});
}
export { getKpimgInfo, extractAndParseBootimg, getInstalledVersion, patch, embedKPM }