harmony-stack-locator 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -2
- package/Windows/351/203/250/347/275/262.md +9 -0
- package/cli.cjs +15 -0
- package/dist/index.html +22 -0
- package/dist/locator.js +180 -0
- package/dist/symbols.js +41 -0
- package/local.cjs +156 -0
- package/package.json +7 -4
- package/windows-start.cjs +56 -0
package/README.md
CHANGED
|
@@ -1,3 +1,20 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 鸿蒙报错定位台
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
在本机解析构建符号 ZIP,支持 ArkTS 行列映射、混淆方法名还原和 C/C++ .so 符号定位。服务只监听本机,不上传日志或符号到公网。
|
|
4
|
+
|
|
5
|
+
## 安装和使用
|
|
6
|
+
|
|
7
|
+
安装 Node.js 22 或更新版。在 Windows 上准备 DevEco Studio Native SDK;启动器会检查 Windows 自带的 tar 和 SDK 中的 LLVM 工具。
|
|
8
|
+
|
|
9
|
+
```powershell
|
|
10
|
+
npm install -g .\harmony-stack-locator-0.1.0.tgz
|
|
11
|
+
harmony-stack-locator
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
如果 PowerShell 阻止命令脚本,使用 `npm.cmd` 和 `harmony-stack-locator.cmd`。
|
|
15
|
+
|
|
16
|
+
然后打开 http://127.0.0.1:4173/,选择对应构建的符号 ZIP、粘贴日志,点击「定位源码」。
|
|
17
|
+
|
|
18
|
+
## 发布
|
|
19
|
+
|
|
20
|
+
用自己的 npm 账号登录后,在包含 `package.json` 的目录运行 `npm publish --access public`,也可以直接发布打好的 .tgz。若包名已被占用,先在 `package.json` 使用自己的 npm 作用域,再重新打包。
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Windows 本机部署(三种符号均支持)
|
|
2
|
+
|
|
3
|
+
1. 解压发布 ZIP,例如解压到 `C:\HarmonyLocator`。确认目录里有 `local.cjs` 和 `dist`。
|
|
4
|
+
2. 安装 Node.js 22 或更新版本。打开 PowerShell,运行 `node -v` 和 `tar.exe --version` 确认工具可用。ZIP 处理使用 Windows 自带的 tar,无需 WSL 或 npm install。
|
|
5
|
+
3. 安装 Windows 版 DevEco Studio 的 Native SDK。双击 `Start-Windows.cmd`。启动器会尝试自动找到原生解析工具;如果没找到,按提示粘贴同时包含 `llvm-readelf.exe` 和 `llvm-addr2line.exe` 的文件夹路径。路径验证通过后会记住,下次不用再填。
|
|
6
|
+
|
|
7
|
+
启动器会检查 ZIP 与原生解析工具,检查失败不会启动不完整的服务。不需要手动设置环境变量。
|
|
8
|
+
|
|
9
|
+
保持 PowerShell 窗口打开,访问 http://127.0.0.1:4173/。选择对应构建的整个符号 ZIP,粘贴日志,点「定位源码」。支持截图格式中的 `1 #26 at ...` 前缀,不必手改。按 Ctrl+C 停止。服务仅监听本机,不对局域网或公网开放。
|
package/cli.cjs
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
const { spawnSync } = require('node:child_process');
|
|
3
|
+
const { join } = require('node:path');
|
|
4
|
+
|
|
5
|
+
if (process.argv.includes('--help') || process.argv.includes('-h')) {
|
|
6
|
+
console.log('harmony-stack-locator — starts the local UI at http://127.0.0.1:4173/');
|
|
7
|
+
console.log('Windows: install the DevEco Native SDK for native symbol resolution.');
|
|
8
|
+
} else if (process.argv.includes('--version')) {
|
|
9
|
+
console.log(require('./package.json').version);
|
|
10
|
+
} else {
|
|
11
|
+
const script = process.platform === 'win32' ? 'windows-start.cjs' : 'local.cjs';
|
|
12
|
+
const result = spawnSync(process.execPath, [join(__dirname, script)], { stdio: 'inherit' });
|
|
13
|
+
if (result.error) console.error(result.error.message);
|
|
14
|
+
process.exitCode = result.status ?? 1;
|
|
15
|
+
}
|
package/dist/index.html
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="zh-CN">
|
|
3
|
+
<meta charset="utf-8">
|
|
4
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
5
|
+
<title>鸿蒙报错定位台</title>
|
|
6
|
+
<style>
|
|
7
|
+
*{box-sizing:border-box}body{margin:0;background:#eef3f8;color:#15273a;font:16px system-ui,sans-serif}header{background:#132a42;color:#fff;padding:32px max(5vw,20px)}header p{color:#c0d5e9;margin-bottom:0}h1{margin:0;font-size:2rem}main{max-width:1080px;margin:28px auto;padding:0 20px}.grid{display:grid;grid-template-columns:1.25fr 1fr;gap:18px}.card{background:#fff;border:1px solid #d6e1eb;border-radius:16px;padding:22px;margin-bottom:18px}h2{font-size:1.15rem;margin:0 0 12px}textarea{width:100%;min-height:180px;resize:vertical}textarea,input{font:inherit;background:#f7fafc;border:1px solid #aebfd0;border-radius:8px;padding:10px;color:inherit}input{width:100%}button{font:inherit;font-weight:650;padding:10px 16px;border:0;border-radius:8px;cursor:pointer;background:#135fb5;color:white}button.secondary{background:#dfeaf6;color:#123e70}.actions{display:flex;gap:12px;flex-wrap:wrap}.hint{color:#435c73;line-height:1.6}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#f0f5fa;padding:16px;border-radius:8px;font-size:14px}@media(max-width:680px){.grid{grid-template-columns:1fr}}
|
|
8
|
+
</style>
|
|
9
|
+
<style>
|
|
10
|
+
.source-input{margin-top:18px}.source-input label{display:block;margin-bottom:8px;font-weight:650}.frame+.frame{margin-top:18px}.frame pre{margin:8px 0}.snippet{overflow:auto;white-space:pre}.code-line{display:block;min-width:max-content}.line-number{display:inline-block;width:4ch;margin-right:1ch;text-align:right;color:#435c73}.target-line{background:#ffdf85;color:#332000;font-weight:700}
|
|
11
|
+
</style>
|
|
12
|
+
<header><h1>鸿蒙报错定位台</h1><p>还原 ArkTS 异常栈,找到对应的源码文件和行号。</p></header>
|
|
13
|
+
<main>
|
|
14
|
+
<div class="grid">
|
|
15
|
+
<section class="card"><h2><label for="stack">1. 粘贴报错日志</label></h2><textarea id="stack" placeholder="粘贴包含调用栈的完整报错"></textarea></section>
|
|
16
|
+
<section class="card"><h2><label for="mapping">2. 选择映射文件</label></h2><input id="mapping" type="file" accept=".map,.json"><p class="hint">选择出错版本同一次构建生成的 sourceMaps.map。工具不校验构建版本,请确认文件匹配。</p><p class="hint">日志和映射仅在浏览器中处理,不上传。</p></section>
|
|
17
|
+
</div>
|
|
18
|
+
<section class="card"><div class="actions"><button id="run">定位源码</button><button class="secondary" id="sample">试用示例</button></div><div class="source-input"><label for="source-files">选择对应版本的源码文件(可选,可多选)</label><input id="source-files" type="file" accept=".ets,.ts,.js" multiple><p class="hint">符号表没有内嵌源码时,选择定位到的文件即可预览。源码也不会上传。</p></div><p class="hint" id="status" role="status">还没有日志?点「试用示例」。</p><h2>定位结果</h2><div id="result">等待分析</div></section>
|
|
19
|
+
</main>
|
|
20
|
+
<script src="locator.js" defer></script>
|
|
21
|
+
<script src="symbols.js" defer></script>
|
|
22
|
+
</html>
|
package/dist/locator.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
const restoreMethodName = typeof module !== 'undefined' ? require('./symbols.js').restoreName
|
|
2
|
+
: (...args) => restoreName(...args);
|
|
3
|
+
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
4
|
+
|
|
5
|
+
function decode(segment) {
|
|
6
|
+
const values = [];
|
|
7
|
+
let value = 0;
|
|
8
|
+
let weight = 1;
|
|
9
|
+
for (const character of segment) {
|
|
10
|
+
const digit = alphabet.indexOf(character);
|
|
11
|
+
if (digit < 0 || weight > 2 ** 45) throw new Error('映射编码无效');
|
|
12
|
+
value += (digit % 32) * weight;
|
|
13
|
+
if (digit >= 32) {
|
|
14
|
+
weight *= 32;
|
|
15
|
+
} else {
|
|
16
|
+
values.push(Math.floor(value / 2) * (value % 2 ? -1 : 1));
|
|
17
|
+
value = 0;
|
|
18
|
+
weight = 1;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
if (weight !== 1 || ![1, 4, 5].includes(values.length)) throw new Error('映射编码无效');
|
|
22
|
+
return values;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function locate(map, line, column) {
|
|
26
|
+
if (map?.version !== 3 || typeof map.mappings !== 'string' || !Array.isArray(map.sources)) return null;
|
|
27
|
+
let source = 0;
|
|
28
|
+
let originalLine = 0;
|
|
29
|
+
let originalColumn = 0;
|
|
30
|
+
let match = null;
|
|
31
|
+
const rows = map.mappings.split(';');
|
|
32
|
+
for (let row = 0; row < line && row < rows.length; row++) {
|
|
33
|
+
let generatedColumn = 0;
|
|
34
|
+
for (const segment of rows[row].split(',').filter(Boolean)) {
|
|
35
|
+
const fields = decode(segment);
|
|
36
|
+
generatedColumn += fields[0];
|
|
37
|
+
if (row === line - 1 && generatedColumn >= column) return match;
|
|
38
|
+
if (fields.length > 1) {
|
|
39
|
+
source += fields[1];
|
|
40
|
+
originalLine += fields[2];
|
|
41
|
+
originalColumn += fields[3];
|
|
42
|
+
}
|
|
43
|
+
if (row === line - 1) {
|
|
44
|
+
match = fields.length > 1 && map.sources[source]
|
|
45
|
+
? { path: map.sources[source], line: originalLine + 1, column: originalColumn + 1,
|
|
46
|
+
content: map.sourcesContent?.[source] } : null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return match;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function analyze(stack, maps, names) {
|
|
54
|
+
if (!maps || typeof maps !== 'object' || Array.isArray(maps)) throw new Error('请选择鸿蒙模块生成的映射文件');
|
|
55
|
+
return stack.split(/\r?\n/).flatMap(frame => {
|
|
56
|
+
const normalized = frame.replace(/^\s*(?:\d+\s+)?#\d+\s+(?=at\s)/, '');
|
|
57
|
+
const position = normalized.match(/^\s*at\s+(?:[^()]*?\()?([^\s()]+):(\d+):(\d+)\)?\s*$/);
|
|
58
|
+
if (!position) return [];
|
|
59
|
+
const [, key, line, column] = position;
|
|
60
|
+
const location = Object.hasOwn(maps, key) && locate(maps[key], Number(line), Number(column));
|
|
61
|
+
const source = location && `${location.path}:${location.line}:${location.column}`;
|
|
62
|
+
const method = normalized.match(/^\s*at\s+(\S+)\s+\(/)?.[1];
|
|
63
|
+
const originalMethod = location && names && restoreMethodName(names, maps[key], location, method);
|
|
64
|
+
return [{ frame: frame.trim(), source, location, originalMethod }];
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (typeof module !== 'undefined') module.exports = { analyze };
|
|
69
|
+
if (typeof document !== 'undefined') {
|
|
70
|
+
const get = id => document.getElementById(id);
|
|
71
|
+
const sampleStack = 'Error: HARMONY_DEMO_TEST_ERROR\n at triggerTestError (entry|entry|1.0.0|src/main/ets/pages/Index.ts:167:9)';
|
|
72
|
+
let sample = false;
|
|
73
|
+
const demoLocation = 'entry/src/main/ets/pages/Index.ets:70:5';
|
|
74
|
+
const demoExcerpt = " }\n\n private triggerTestError(): void {\n throw new Error('HARMONY_DEMO_TEST_ERROR');\n }\n}";
|
|
75
|
+
async function renderFrame(item, files, useDemo) {
|
|
76
|
+
const card = document.createElement('article');
|
|
77
|
+
card.className = 'frame';
|
|
78
|
+
const stackFrame = document.createElement('pre');
|
|
79
|
+
stackFrame.textContent = item.frame;
|
|
80
|
+
card.append(stackFrame);
|
|
81
|
+
const heading = document.createElement('strong');
|
|
82
|
+
heading.textContent = item.source || item.detail || '未匹配:请检查映射文件是否来自同一次构建。';
|
|
83
|
+
card.append(heading);
|
|
84
|
+
if (item.originalMethod) {
|
|
85
|
+
const method = document.createElement('p');
|
|
86
|
+
method.textContent = `函数:${item.originalMethod}`;
|
|
87
|
+
card.append(method);
|
|
88
|
+
}
|
|
89
|
+
if (!item.location) return card;
|
|
90
|
+
|
|
91
|
+
const { path, line, content } = item.location;
|
|
92
|
+
const sameName = files.filter(file => file.name === path.split(/[\\/]/).pop());
|
|
93
|
+
const isDemo = useDemo && item.source === demoLocation;
|
|
94
|
+
const code = typeof content === 'string' ? content
|
|
95
|
+
: sameName.length === 1 ? await sameName[0].text() : isDemo ? demoExcerpt : null;
|
|
96
|
+
const firstLine = typeof content !== 'string' && sameName.length === 0 && isDemo ? 67 : 1;
|
|
97
|
+
const lines = code?.split(/\r\n|\n|\r/);
|
|
98
|
+
const index = line - firstLine;
|
|
99
|
+
if (!lines || index < 0 || index >= lines.length) {
|
|
100
|
+
const hint = document.createElement('p');
|
|
101
|
+
hint.className = 'hint';
|
|
102
|
+
hint.textContent = sameName.length > 1 ? '选了多个同名文件,请只保留对应路径的文件。'
|
|
103
|
+
: '无法预览源码,请选择同一次构建所用的对应源码文件,再点「定位源码」。';
|
|
104
|
+
card.append(hint);
|
|
105
|
+
return card;
|
|
106
|
+
}
|
|
107
|
+
const snippet = document.createElement('pre');
|
|
108
|
+
snippet.className = 'snippet';
|
|
109
|
+
snippet.setAttribute('aria-label', `源码预览,报错行第 ${line} 行`);
|
|
110
|
+
for (let row = Math.max(0, index - 3); row <= Math.min(lines.length - 1, index + 3); row++) {
|
|
111
|
+
const codeLine = document.createElement('span');
|
|
112
|
+
codeLine.className = row === index ? 'code-line target-line' : 'code-line';
|
|
113
|
+
const number = document.createElement('span');
|
|
114
|
+
number.className = 'line-number';
|
|
115
|
+
number.textContent = row + firstLine;
|
|
116
|
+
codeLine.append(number, lines[row]);
|
|
117
|
+
snippet.append(codeLine);
|
|
118
|
+
}
|
|
119
|
+
card.append(snippet);
|
|
120
|
+
return card;
|
|
121
|
+
}
|
|
122
|
+
get('mapping').onchange = () => { sample = false; get('status').textContent = '已选择文件,可以开始定位。'; };
|
|
123
|
+
async function run() {
|
|
124
|
+
const button = get('run');
|
|
125
|
+
button.disabled = true;
|
|
126
|
+
get('result').textContent = '正在分析…';
|
|
127
|
+
try {
|
|
128
|
+
const stack = get('stack').value.trim();
|
|
129
|
+
if (!stack) throw new Error('请先粘贴报错日志');
|
|
130
|
+
const archive = get('symbol-archive').files[0];
|
|
131
|
+
if (archive) {
|
|
132
|
+
const results = await resolveNative(stack, archive, '/archive');
|
|
133
|
+
const files = Array.from(get('source-files').files);
|
|
134
|
+
const frames = await Promise.all(results.map(item => renderFrame(item, files, false)));
|
|
135
|
+
get('result').replaceChildren(...(frames.length ? frames : ['没有识别到 ArkTS 或 C/C++ 栈帧。']));
|
|
136
|
+
get('status').textContent = `已还原 ${results.filter(item => item.source).length} / ${results.length} 个栈帧 · ${archive.name}`;
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const nativeFile = get('native-symbol').files[0];
|
|
140
|
+
const nameFile = get('name-cache').files[0];
|
|
141
|
+
if (nativeFile && (nameFile || get('mapping').files[0])) throw new Error('请分开解析 ArkTS 和 C/C++ 符号。');
|
|
142
|
+
if (nativeFile) {
|
|
143
|
+
const results = await resolveNative(stack, nativeFile);
|
|
144
|
+
const files = Array.from(get('source-files').files);
|
|
145
|
+
get('result').replaceChildren(...await Promise.all(results.map(item => renderFrame(item, files, false))));
|
|
146
|
+
get('status').textContent = `已还原 ${results.filter(item => item.source).length} / ${results.length} 个原生栈帧`;
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
const file = get('mapping').files[0];
|
|
150
|
+
if (!file && !sample) throw new Error('请先选择对应版本的 sourceMaps.map');
|
|
151
|
+
const maps = file ? JSON.parse(await file.text()) : {
|
|
152
|
+
'entry|entry|1.0.0|src/main/ets/pages/Index.ts': {
|
|
153
|
+
version: 3, sources: ['entry/src/main/ets/pages/Index.ets'], mappings: ';'.repeat(166) + 'QAqEK'
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
const names = nameFile ? JSON.parse(await nameFile.text()) : null;
|
|
157
|
+
const results = analyze(stack, maps, names);
|
|
158
|
+
get('status').textContent = `${sample ? '演示数据(非真实运行日志) · ' : ''}已还原 ${results.filter(item => item.source).length} / ${results.length} 个栈帧`;
|
|
159
|
+
const files = Array.from(get('source-files').files);
|
|
160
|
+
const frames = await Promise.all(results.map(item => renderFrame(item, files, sample && !file)));
|
|
161
|
+
get('result').replaceChildren(...(frames.length ? frames : ['未找到包含文件、行号和列号的栈帧。']));
|
|
162
|
+
} catch (error) {
|
|
163
|
+
get('status').textContent = '无法分析';
|
|
164
|
+
get('result').textContent = error.message;
|
|
165
|
+
} finally {
|
|
166
|
+
button.disabled = false;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
get('run').onclick = run;
|
|
170
|
+
get('sample').onclick = () => {
|
|
171
|
+
get('stack').value = sampleStack;
|
|
172
|
+
get('mapping').value = '';
|
|
173
|
+
get('symbol-archive').value = '';
|
|
174
|
+
get('name-cache').value = '';
|
|
175
|
+
get('native-symbol').value = '';
|
|
176
|
+
get('source-files').value = '';
|
|
177
|
+
sample = true;
|
|
178
|
+
run();
|
|
179
|
+
};
|
|
180
|
+
}
|
package/dist/symbols.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
function restoreName(cache, map, location, method) {
|
|
2
|
+
if (!method || !cache || typeof cache !== 'object') return null;
|
|
3
|
+
if (cache.entryPackageInfo && cache.entryPackageInfo !== map['entry-package-info']) return null;
|
|
4
|
+
const path = location.path.replaceAll('\\', '/');
|
|
5
|
+
const matches = new Set();
|
|
6
|
+
for (const [key, entry] of Object.entries(cache)) {
|
|
7
|
+
if (key.replaceAll('\\', '/') !== path || !entry) continue;
|
|
8
|
+
for (const table of [entry.IdentifierCache, entry.MemberMethodCache]) {
|
|
9
|
+
for (const [signature, alias] of Object.entries(table ?? {})) {
|
|
10
|
+
const range = signature.match(/^(.*):(\d+):(\d+)$/);
|
|
11
|
+
if (alias === method && range && location.line >= Number(range[2]) && location.line <= Number(range[3])) {
|
|
12
|
+
matches.add(range[1].split('#').pop());
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return matches.size === 1 ? [...matches][0] : null;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function resolveNative(stack, file, endpoint = '/native') {
|
|
21
|
+
if (!['localhost', '127.0.0.1'].includes(window.location.hostname)) {
|
|
22
|
+
throw new Error('原生 .so 解析需在本机版运行;在线版不会上传你的二进制文件。');
|
|
23
|
+
}
|
|
24
|
+
if (file.size > 64 * 1024 * 1024) throw new Error('符号文件超过 64 MB');
|
|
25
|
+
const response = await fetch(endpoint, {
|
|
26
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
27
|
+
body: new Blob([JSON.stringify({ stack, name: file.name }) + '\n', file], { type: 'application/octet-stream' })
|
|
28
|
+
});
|
|
29
|
+
const result = await response.json();
|
|
30
|
+
if (!response.ok) throw new Error(result.error);
|
|
31
|
+
return result;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (typeof module !== 'undefined') module.exports = { restoreName };
|
|
35
|
+
if (typeof document !== 'undefined') {
|
|
36
|
+
const panel = document.getElementById('mapping').parentElement;
|
|
37
|
+
const inputs = document.createElement('div');
|
|
38
|
+
inputs.innerHTML = '<p><label><strong>构建符号包 ZIP(本机版)</strong><input type="file" id="symbol-archive" accept=".zip"></label></p><p class="hint">选择一次 ZIP,后续可直接换日志。选了 ZIP 就无需再逐个选符号文件。</p><details><summary>单文件模式:更多符号选项</summary><p><label>混淆名称映射 nameCache.json(可选)<input type="file" id="name-cache" accept=".json"></label></p><p><label>C/C++ 调试符号 .so(本机版)<input type="file" id="native-symbol" accept=".so"></label></p></details>';
|
|
39
|
+
panel.append(inputs);
|
|
40
|
+
panel.prepend(inputs);
|
|
41
|
+
}
|
package/local.cjs
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
const { createServer } = require('node:http');
|
|
2
|
+
const { execFile } = require('node:child_process');
|
|
3
|
+
const { promisify } = require('node:util');
|
|
4
|
+
const { mkdtemp, readFile, writeFile, unlink, rmdir } = require('node:fs/promises');
|
|
5
|
+
const { tmpdir } = require('node:os');
|
|
6
|
+
const { join } = require('node:path');
|
|
7
|
+
|
|
8
|
+
const exec = promisify(execFile);
|
|
9
|
+
const windows = process.platform === 'win32';
|
|
10
|
+
const llvm = process.env.HARMONY_LLVM || (windows ? null : '/Applications/DevEco-Studio.app/Contents/sdk/default/openharmony/native/llvm/bin');
|
|
11
|
+
const llvmTool = name => llvm ? join(llvm, windows ? `${name}.exe` : name) : `${name}.exe`;
|
|
12
|
+
const archiveTool = windows ? join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe') : '/usr/bin/unzip';
|
|
13
|
+
const port = 4173;
|
|
14
|
+
const origin = `http://127.0.0.1:${port}`;
|
|
15
|
+
const assets = new Map([['/', ['index.html', 'text/html']], ['/locator.js', ['locator.js', 'text/javascript']], ['/symbols.js', ['symbols.js', 'text/javascript']]]);
|
|
16
|
+
const { analyze } = require('./dist/locator.js');
|
|
17
|
+
|
|
18
|
+
async function resolveArchive(stack, bytes) {
|
|
19
|
+
const dir = await mkdtemp(join(tmpdir(), 'harmony-archive-'));
|
|
20
|
+
const file = join(dir, 'symbols.zip');
|
|
21
|
+
const options = { timeout: 5000, maxBuffer: 16 * 1024 * 1024 };
|
|
22
|
+
try {
|
|
23
|
+
await writeFile(file, bytes);
|
|
24
|
+
const { stdout } = await exec(archiveTool, [windows ? '-tf' : '-Z1', file], options);
|
|
25
|
+
const entries = stdout.trimEnd().split(/\r?\n/).filter(entry =>
|
|
26
|
+
/^(?:[\w.+-]+\/)*(?:sourceMaps\.map|nameCache\.json|lib[\w.+-]+\.so)$/.test(entry) &&
|
|
27
|
+
!entry.split('/').some(part => part === '.' || part === '..'));
|
|
28
|
+
if (!entries.length || entries.length > 128 || new Set(entries).size !== entries.length) {
|
|
29
|
+
throw new Error('ZIP 中没有可识别的符号文件,或符号数量过多、路径重复。');
|
|
30
|
+
}
|
|
31
|
+
let expandedBytes = 0;
|
|
32
|
+
async function read(entry) {
|
|
33
|
+
const { stdout: contents } = await exec(archiveTool, [windows ? '-xOf' : '-p', file, entry], { ...options, encoding: 'buffer' });
|
|
34
|
+
expandedBytes += contents.length;
|
|
35
|
+
if (expandedBytes > 64 * 1024 * 1024) throw new Error('解压后的符号文件超过 64 MB。');
|
|
36
|
+
return contents;
|
|
37
|
+
}
|
|
38
|
+
const maps = [];
|
|
39
|
+
const native = new Map();
|
|
40
|
+
for (const entry of entries) {
|
|
41
|
+
if (entry.endsWith('/sourceMaps.map') || entry === 'sourceMaps.map') {
|
|
42
|
+
const sibling = entry.replace(/sourceMaps\.map$/, 'nameCache.json');
|
|
43
|
+
maps.push([JSON.parse(await read(entry)), entries.includes(sibling) ? JSON.parse(await read(sibling)) : null]);
|
|
44
|
+
}
|
|
45
|
+
if (entry.endsWith('.so')) {
|
|
46
|
+
const name = entry.split('/').pop();
|
|
47
|
+
if (!native.has(name)) native.set(name, []);
|
|
48
|
+
native.get(name).push(entry);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const cache = new Map();
|
|
52
|
+
const results = [];
|
|
53
|
+
for (const rawFrame of stack.split(/\r?\n/)) {
|
|
54
|
+
const frame = rawFrame.replace(/^\s*\d+\s+(?=#\d+\s+pc\b)/i, '');
|
|
55
|
+
const lib = frame.match(/^\s*#\d+\s+pc\s+[\da-f]+\s+(\S+)/i)?.[1]?.split('/').pop();
|
|
56
|
+
if (lib) {
|
|
57
|
+
const matches = [];
|
|
58
|
+
for (const entry of native.get(lib) ?? []) {
|
|
59
|
+
if (!cache.has(entry)) cache.set(entry, await read(entry));
|
|
60
|
+
try {
|
|
61
|
+
const [result] = await symbolize(frame, lib, cache.get(entry));
|
|
62
|
+
matches.push(result);
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (!error.message.startsWith('Build ID')) throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const valid = matches.filter(item => item.source);
|
|
68
|
+
results.push(valid.length === 1 ? valid[0] : { frame, source: null, detail: valid.length > 1
|
|
69
|
+
? '符号包包含多份可用的同名库。' : '未找到 Build ID 匹配且包含调试行号的原生库。' });
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
const [parsed] = analyze(frame, {});
|
|
73
|
+
if (!parsed) continue;
|
|
74
|
+
const matches = maps.flatMap(([map, names]) => analyze(frame, map, names)).filter(item => item.source);
|
|
75
|
+
results.push(matches.length === 1 ? matches[0] : { ...parsed, detail: matches.length
|
|
76
|
+
? '多个模块的映射都匹配,无法唯一定位。' : '符号包中没有匹配的 ArkTS 映射位置。' });
|
|
77
|
+
}
|
|
78
|
+
return results;
|
|
79
|
+
} finally {
|
|
80
|
+
await unlink(file).catch(() => {});
|
|
81
|
+
await rmdir(dir);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function symbolize(stack, name, bytes) {
|
|
86
|
+
if (!/^lib[\w.+-]+\.so$/.test(name) || bytes.subarray(0, 4).toString('hex') !== '7f454c46') {
|
|
87
|
+
throw new Error('请选择有效的 ELF .so 调试符号文件。');
|
|
88
|
+
}
|
|
89
|
+
const frames = stack.split(/\r?\n/).flatMap(frame => {
|
|
90
|
+
const match = frame.match(/^\s*#\d+\s+pc\s+([\da-f]+)\s+(\S+)(.*)$/i);
|
|
91
|
+
if (!match || match[2].split('/').pop() !== name) return [];
|
|
92
|
+
const build = match[3].match(/\bBuild\s*ID\s*[:=]?\s*([\da-f]{8,})\b/i)
|
|
93
|
+
|| match[3].match(/\(([\da-f]{8,})\)\s*$/i);
|
|
94
|
+
return [{ frame: frame.trim(), offset: match[1], build: build?.[1].toLowerCase() }];
|
|
95
|
+
});
|
|
96
|
+
if (!frames.length || frames.length > 100) throw new Error('请提供 1 到 100 个与此 .so 同名的 pc 栈帧。');
|
|
97
|
+
const dir = await mkdtemp(join(tmpdir(), 'harmony-symbol-'));
|
|
98
|
+
const file = join(dir, 'symbols.so');
|
|
99
|
+
try {
|
|
100
|
+
await writeFile(file, bytes);
|
|
101
|
+
const { stdout: notes } = await exec(llvmTool('llvm-readelf'), ['-n', file], { timeout: 5000 });
|
|
102
|
+
const id = notes.match(/Build ID:\s*([\da-f]+)/i)?.[1].toLowerCase();
|
|
103
|
+
if (!id || frames.some(frame => frame.build !== id)) throw new Error('Build ID 缺失或不匹配,拒绝还原。');
|
|
104
|
+
const { stdout } = await exec(llvmTool('llvm-addr2line'), ['-f', '-C', '-e', file, ...frames.map(frame => `0x${frame.offset}`)], { timeout: 8000 });
|
|
105
|
+
const lines = stdout.trimEnd().split(/\r?\n/);
|
|
106
|
+
return frames.map(({ frame }, index) => {
|
|
107
|
+
const source = lines[index * 2 + 1]?.match(/^(.*):(\d+)(?:\s+.*)?$/);
|
|
108
|
+
const location = source && source[1] !== '??' && Number(source[2]) > 0
|
|
109
|
+
? { path: source[1], line: Number(source[2]) } : null;
|
|
110
|
+
const method = lines[index * 2];
|
|
111
|
+
return { frame, source: location && `${location.path}:${location.line}`, location,
|
|
112
|
+
originalMethod: method === '??' ? null : method };
|
|
113
|
+
});
|
|
114
|
+
} finally {
|
|
115
|
+
await unlink(file).catch(() => {});
|
|
116
|
+
await rmdir(dir);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (require.main === module) createServer(async (request, response) => {
|
|
121
|
+
try {
|
|
122
|
+
if (request.headers.host !== `127.0.0.1:${port}`) {
|
|
123
|
+
response.writeHead(403).end();
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const asset = request.method === 'GET' && assets.get(request.url);
|
|
127
|
+
if (asset) {
|
|
128
|
+
const body = await readFile(join(__dirname, 'dist', asset[0]));
|
|
129
|
+
response.writeHead(200, { 'Content-Type': `${asset[1]};charset=utf-8` }).end(body);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (request.method !== 'POST' || !['/native', '/archive'].includes(request.url) || request.headers.origin !== origin) {
|
|
133
|
+
response.writeHead(404).end();
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const chunks = [];
|
|
137
|
+
let size = 0;
|
|
138
|
+
for await (const chunk of request) {
|
|
139
|
+
size += chunk.length;
|
|
140
|
+
if (size > 65 * 1024 * 1024) throw new Error('文件太大。');
|
|
141
|
+
chunks.push(chunk);
|
|
142
|
+
}
|
|
143
|
+
const body = Buffer.concat(chunks);
|
|
144
|
+
const boundary = body.indexOf(10);
|
|
145
|
+
if (boundary <= 0 || boundary > 1024 * 1024) throw new Error('日志头无效或过长。');
|
|
146
|
+
const { stack, name } = JSON.parse(body.subarray(0, boundary).toString());
|
|
147
|
+
if (typeof stack !== 'string' || typeof name !== 'string') throw new Error('日志或文件名无效。');
|
|
148
|
+
const result = request.url === '/archive' ? await resolveArchive(stack, body.subarray(boundary + 1))
|
|
149
|
+
: await symbolize(stack, name, body.subarray(boundary + 1));
|
|
150
|
+
response.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify(result));
|
|
151
|
+
} catch (error) {
|
|
152
|
+
response.writeHead(400, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: error.code ? 'LLVM 解析失败,请检查 DevEco SDK 工具或符号文件。' : error.message }));
|
|
153
|
+
}
|
|
154
|
+
}).listen(port, '127.0.0.1', () => console.log(origin));
|
|
155
|
+
|
|
156
|
+
module.exports = { symbolize, resolveArchive };
|
package/package.json
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "harmony-stack-locator",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
}
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Local HarmonyOS ArkTS and native crash stack symbolicator",
|
|
5
|
+
"bin": { "harmony-stack-locator": "cli.cjs" },
|
|
6
|
+
"engines": { "node": ">=22" },
|
|
7
|
+
"files": ["cli.cjs", "local.cjs", "windows-start.cjs", "dist/", "Windows部署.md"],
|
|
8
|
+
"publishConfig": { "access": "public" }
|
|
9
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
const { accessSync, mkdirSync, readFileSync, writeFileSync } = require('node:fs');
|
|
2
|
+
const { homedir } = require('node:os');
|
|
3
|
+
const { join, resolve } = require('node:path');
|
|
4
|
+
const { spawnSync } = require('node:child_process');
|
|
5
|
+
const { createInterface } = require('node:readline/promises');
|
|
6
|
+
|
|
7
|
+
const tools = ['llvm-readelf.exe', 'llvm-addr2line.exe'];
|
|
8
|
+
const settingsFolder = join(process.env.LOCALAPPDATA || homedir(), 'HarmonyStackLocator');
|
|
9
|
+
const settings = join(settingsFolder, 'llvm-directory');
|
|
10
|
+
const works = (command, args = ['--version']) =>
|
|
11
|
+
spawnSync(command, args, { stdio: 'ignore', timeout: 5000 }).status === 0;
|
|
12
|
+
|
|
13
|
+
function valid(directory) {
|
|
14
|
+
if (!directory) return false;
|
|
15
|
+
return tools.every(tool => {
|
|
16
|
+
const file = join(directory, tool);
|
|
17
|
+
try { accessSync(file); } catch { return false; }
|
|
18
|
+
return works(file);
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function start() {
|
|
23
|
+
if (process.platform !== 'win32') throw new Error('This launcher is for Windows.');
|
|
24
|
+
if (Number(process.versions.node.split('.')[0]) < 22) throw new Error('Install Node.js 22 or newer.');
|
|
25
|
+
if (!works(join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe'))) {
|
|
26
|
+
throw new Error('Windows tar.exe is unavailable. It is required to read symbol ZIP files.');
|
|
27
|
+
}
|
|
28
|
+
let saved;
|
|
29
|
+
try { saved = readFileSync(settings, 'utf8').trim(); } catch {}
|
|
30
|
+
const folders = [process.env.DEVECO_SDK_HOME,
|
|
31
|
+
join(process.env.ProgramFiles || 'C:\\Program Files', 'Huawei', 'DevEco Studio', 'sdk'),
|
|
32
|
+
join(process.env.LOCALAPPDATA || '.', 'Huawei', 'Sdk')];
|
|
33
|
+
let directory = [saved, process.env.HARMONY_LLVM, ...folders.filter(Boolean)
|
|
34
|
+
.map(folder => join(folder, 'default', 'openharmony', 'native', 'llvm', 'bin'))].find(valid);
|
|
35
|
+
if (!directory && !tools.every(tool => works(tool))) {
|
|
36
|
+
const input = createInterface({ input: process.stdin, output: process.stdout });
|
|
37
|
+
try {
|
|
38
|
+
const answer = await input.question('Paste the DevEco LLVM bin folder (contains llvm-readelf.exe and llvm-addr2line.exe): ');
|
|
39
|
+
directory = answer.trim().replace(/^"(.*)"$/, '$1');
|
|
40
|
+
if (!valid(directory)) throw new Error('Both LLVM tools must exist and run. Install the DevEco Native SDK, then try again.');
|
|
41
|
+
directory = resolve(directory);
|
|
42
|
+
mkdirSync(settingsFolder, { recursive: true });
|
|
43
|
+
writeFileSync(settings, directory, 'utf8');
|
|
44
|
+
} finally {
|
|
45
|
+
input.close();
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (directory) process.env.HARMONY_LLVM = directory;
|
|
49
|
+
else delete process.env.HARMONY_LLVM;
|
|
50
|
+
console.log('ArkTS mapping, name restoration, and native symbol tools are ready.');
|
|
51
|
+
const result = spawnSync(process.execPath, [join(__dirname, 'local.cjs')], { stdio: 'inherit' });
|
|
52
|
+
if (result.error) throw result.error;
|
|
53
|
+
process.exitCode = result.status ?? 1;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
start().catch(error => { console.error(error.message); process.exitCode = 1; });
|