-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSourceMapper.ts
More file actions
231 lines (196 loc) · 7.85 KB
/
SourceMapper.ts
File metadata and controls
231 lines (196 loc) · 7.85 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
import {SourceMap} from './SourceMap';
import {exec, ExecException} from 'child_process';
import * as fs from 'fs';
import {MappingItem, SourceMapConsumer} from 'source-map';
import SourceLine = SourceMap.SourceLine;
import Mapping = SourceMap.Mapping;
import Closure = SourceMap.Closure;
import Variable = SourceMap.Variable;
import TargetInstruction = SourceMap.TargetInstruction;
import {find} from '../util/util';
export abstract class SourceMapper {
abstract mapping(): Promise<Mapping>;
}
// Maps Wasm to WAT
export class WatMapper implements SourceMapper {
private readonly tmpdir: string;
private readonly wabt: string;
private lineMapping: SourceMap.SourceLine[];
constructor(compileOutput: string, tmpdir: string, wabt: string) {
this.lineMapping = [];
this.parse(compileOutput);
this.wabt = wabt;
this.tmpdir = tmpdir;
}
public mapping(): Promise<Mapping> {
return new Promise<Mapping>((resolve, reject) => {
let functions: Closure[];
let globals: Variable[];
let imports: Closure[];
let sourceMap: Mapping;
function handleObjDumpStreams(error: ExecException | null, stdout: string, stderr: string) {
if (stderr.match('wasm-objdump')) {
reject('Could not find wasm-objdump in the path');
} else if (error) {
reject(error.message);
}
try {
functions = WatMapper.getFunctionInfos(stdout);
globals = WatMapper.getGlobalInfos(stdout);
imports = WatMapper.getImportInfos(stdout);
} catch (e) {
reject(e);
}
}
const objDump = exec(this.getNameDumpCommand(), handleObjDumpStreams);
sourceMap = new SourceMap.Mapping().init(this.lineMapping, [], [], []);
objDump.on('close', () => {
sourceMap.functions = functions;
sourceMap.globals = globals;
sourceMap.imports = imports;
resolve(sourceMap);
});
});
}
private parse(compileOutput: string) {
this.lineMapping = [];
const lines = compileOutput.split('\n');
for (let i = 0; i < lines.length; i++) {
if (lines[i].match(/^@ {/)) {
const mapping: SourceLine = WatMapper.extractLineInfo(lines[i]);
mapping.instructions = WatMapper.extractAddressInfo(lines[i + 1]);
this.lineMapping.push(mapping);
}
}
}
private static extractLineInfo(line: string): SourceLine {
const obj = JSON.parse(line.substring(2));
return {line: obj.line, columnStart: obj.col_start - 1, columnEnd: obj.col_end, instructions: []};
}
private static extractAddressInfo(line?: string): TargetInstruction[] {
if (line === undefined) {
return [];
}
const regexpr = /^(?<address>([\da-f])+):/;
const match = line.match(regexpr);
if (match?.groups) {
return [{address: parseInt(match.groups.address, 16)}];
}
throw Error(`Could not parse address from line: ${line}`);
}
private static getFunctionInfos(input: string): Closure[] {
const functionLines: string[] = extractMajorSection('Function', input);
if (functionLines.length === 0) {
throw Error('Could not messaging \'sourcemap\' section of objdump');
}
const functions: Closure[] = [];
functionLines.forEach((line: string) => {
const fidx: number = +find(/func\[([0-9]+)/, line.toString());
const name: string = find(/<(.*)>/, line.toString());
const locals: Variable[] = [];
const matches: string[] = input.match(new RegExp(`(func\[${fidx}\][^\n]*)`, 'g')) ?? [];
// eslint-disable-next-line
for (const text in matches) {
const index: number = +find(/func\[([0-9]+)/, line.toString());
const local: string = find(/<(.*)>/, line.toString());
locals.push({index: index, name: local, type: 'undefined', mutable: true, value: ''});
}
functions.push({index: fidx, name: name, arguments: [], locals: locals});
})
return functions;
}
private static getGlobalInfos(input: string): Variable[] {
const lines: string[] = extractDetailedSection('Global[', input);
const globals: Variable[] = [];
lines.forEach((line) => {
globals.push(extractGlobalInfo(line));
});
return globals;
}
private static getImportInfos(input: string): Closure[] {
const lines: string[] = extractDetailedSection('Import[', input);
const globals: Closure[] = [];
lines.forEach((line) => {
globals.push(extractImportInfo(line));
});
return globals;
}
private getNameDumpCommand(): string {
return `${this.wabt}/wasm-objdump -x -m ${this.tmpdir}/upload.wasm`;
}
}
function extractDetailedSection(section: string, input: string): string[] {
const lines = input.split('\n');
let i = 0;
while (i < lines.length && !lines[i].startsWith(section)) {
i++;
}
if (i >= lines.length) {
return [];
}
const count: number = +(lines[i++].split(/[[]+/)[1]);
return lines.slice(i, ((isNaN(count)) ? lines.length : i + count));
}
function extractMajorSection(section: string, input: string): string[] {
const lines = input.split('\n');
let i = 0;
while (i < lines.length && !lines[i].startsWith(section)) {
i++;
}
i += 2;
const start = i;
while (i < lines.length && lines[i] !== '') {
i++;
}
return lines.slice(start, i);
}
function extractGlobalInfo(line: string): Variable {
const global = {} as Variable;
let match = line.match(/\[([0-9]+)]/);
global.index = (match === null) ? NaN : +match[1];
match = line.match(/ ([if][0-9][0-9]) /);
global.type = (match === null) ? 'undefined' : match[1];
match = line.match(/<([a-zA-Z0-9 ._]+)>/);
global.name = ((match === null) ? `${global.index}` : `$${match[1]}`) + ` (${global.type})`;
match = line.match(/mutable=([0-9])/);
global.mutable = match !== null && +match[1] === 1;
match = line.match(/init.*=(.*)/);
global.value = (match === null) ? '' : match[1];
return global;
}
function extractImportInfo(line: string): Closure {
const primitive = {} as Closure;
let match = line.match(/\[([0-9]+)]/);
primitive.index = (match === null) ? NaN : +match[1];
match = line.match(/<([a-zA-Z0-9 ._]+)>/);
primitive.name = ((match === null) ? `${primitive.index}` : `$${match[1]}`);
return primitive;
}
// Maps Wasm to AS
export class AsScriptMapper implements SourceMapper {
private readonly sourceFile: string;
private readonly tmpdir: string;
constructor(sourceFile: string, tmpdir: string) {
this.sourceFile = sourceFile;
this.tmpdir = tmpdir;
}
public mapping(): Promise<Mapping> {
const input = fs.readFileSync(`${this.tmpdir}/upload.wasm.map`)
return new Promise((resolve) => {
new SourceMapConsumer(input.toString()).then((consumer: SourceMapConsumer) => {
const mapping: Mapping = new SourceMap.Mapping().init([], [], [], []);
consumer.eachMapping(function (item: MappingItem) {
mapping.lines.push({
line: item.originalLine,
columnStart: item.originalColumn,
instructions: [{
address: item.generatedColumn
}],
source: item.source
})
});
resolve(mapping);
});
});
}
}