-
-
Notifications
You must be signed in to change notification settings - Fork 687
Expand file tree
/
Copy pathindex.js
More file actions
346 lines (311 loc) · 10.2 KB
/
index.js
File metadata and controls
346 lines (311 loc) · 10.2 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
// WebAssembly pages are 65536 kb
const PAGE_SIZE_BITS = 16;
const PAGE_SIZE = 1 << PAGE_SIZE_BITS;
const PAGE_MASK = PAGE_SIZE - 1;
// Wasm32 pointer size is 4 bytes
const PTR_SIZE_BITS = 2;
const PTR_SIZE = 1 << PTR_SIZE_BITS;
const PTR_MASK = PTR_SIZE - 1;
const PTR_VIEW = Uint32Array;
export const BLOCK_OVERHEAD = PTR_SIZE;
export const OBJECT_OVERHEAD = 16;
export const TOTAL_OVERHEAD = BLOCK_OVERHEAD + OBJECT_OVERHEAD;
function assert(x) {
if (!x) throw Error("assertion failed");
return x;
}
Error.stackTraceLimit = 15;
function trimStacktrace(stack, levels) {
return stack.split(/\r?\n/).slice(1 + levels);
}
const hrtime = typeof performance !== "undefined" && performance.now
? performance.now
: typeof process !== "undefined" && process.hrtime
? () => { let t = process.hrtime(); return t[0] * 1e3 + t[1] / 1e6; }
: Date.now;
const mmTagsToString = [
"",
"FREE",
"LEFTFREE",
"FREE+LEFTFREE"
];
const gcColorToString = [
"BLACK/WHITE",
"WHITE/BLACK",
"GRAY",
"INVALID"
];
export class Rtrace {
constructor(options) {
this.options = options || {};
this.onerror = this.options.onerror || function() { /* nop */ };
this.oninfo = this.options.oninfo || function() { /* nop */ };
this.oncollect_ = this.options.oncollect || function() { /* nop */ };
this.memory = null;
this.shadow = null;
this.shadowStart = 0x100000000;
this.blocks = new Map();
this.allocSites = new Map();
this.freedBlocks = new Map();
this.gcProfileStart = 0;
this.gcProfile = [];
this.allocCount = 0;
this.resizeCount = 0;
this.moveCount = 0;
this.freeCount = 0;
this.heapBase = 0x100000000;
}
install(imports) {
if (!imports) imports = {};
imports.rtrace = Object.assign(imports.rtrace || {}, {
oninit: this.oninit.bind(this),
onalloc: this.onalloc.bind(this),
onresize: this.onresize.bind(this),
onmove: this.onmove.bind(this),
onvisit: this.onvisit.bind(this),
onfree: this.onfree.bind(this),
oninterrupt: this.oninterrupt.bind(this),
onyield: this.onyield.bind(this),
oncollect: this.oncollect.bind(this),
onstore: this.onstore.bind(this),
onload: this.onload.bind(this)
});
return imports;
}
/** Synchronizes the shadow memory with the module's memory. */
syncShadow() {
if (!this.memory) {
this.memory = assert(this.options.getMemory());
this.shadow = new WebAssembly.Memory({
initial: ((this.memory.buffer.byteLength + PAGE_MASK) & ~PAGE_MASK) >>> PAGE_SIZE_BITS
});
} else {
let diff = this.memory.buffer.byteLength - this.shadow.buffer.byteLength;
if (diff > 0) this.shadow.grow(diff >>> 16);
}
}
/** Marks a block's presence in shadow memory. */
markShadow(info, oldSize = 0) {
assert(this.shadow && this.shadow.byteLength == this.memory.byteLength);
assert((info.size & PTR_MASK) == 0);
if (info.ptr < this.shadowStart) {
this.shadowStart = info.ptr;
}
let len = info.size >>> PTR_SIZE_BITS;
let view = new PTR_VIEW(this.shadow.buffer, info.ptr, len);
let errored = false;
let start = oldSize >>> PTR_SIZE_BITS;
for (let i = 0; i < start; ++i) {
if (view[i] != info.ptr && !errored) {
this.onerror(Error("shadow region mismatch: " + view[i] + " != " + info.ptr), info);
errored = true;
}
}
errored = false;
for (let i = start; i < len; ++i) {
if (view[i] != 0 && !errored) {
this.onerror(Error("shadow region already in use: " + view[i] + " != 0"), info);
errored = true;
}
view[i] = info.ptr;
}
}
/** Unmarks a block's presence in shadow memory. */
unmarkShadow(info, oldSize = info.size) {
assert(this.shadow && this.shadow.byteLength == this.memory.byteLength);
let len = oldSize >>> PTR_SIZE_BITS;
let view = new PTR_VIEW(this.shadow.buffer, info.ptr, len);
let errored = false;
let start = 0;
if (oldSize != info.size) {
assert(oldSize > info.size);
start = info.size >>> PTR_SIZE_BITS;
}
for (let i = 0; i < len; ++i) {
if (view[i] != info.ptr && !errored) {
this.onerror(Error("shadow region mismatch: " + view[i] + " != " + info.ptr), info);
errored = true;
}
if (i >= start) view[i] = 0;
}
}
/** Performs an access to shadow memory. */
accessShadow(ptr, size, isLoad, isRT) {
this.syncShadow();
if (ptr < this.shadowStart) return;
let value = new Uint32Array(this.shadow.buffer, ptr & ~PTR_MASK, 1)[0];
if (value != 0) return;
if (!isRT) {
let stack = trimStacktrace(new Error().stack, 2);
this.onerror(new Error("OOB " + (isLoad ? "load" : "store") + (8 * size) + " at address " + ptr + "\n" + stack.join("\n")));
}
}
/** Obtains information about a block. */
getBlockInfo(ptr) {
const [
mmInfo,
gcInfo,
gcInfo2,
rtId,
rtSize
] = new Uint32Array(this.memory.buffer, ptr, 5);
const size = mmInfo & ~3;
return {
ptr,
size: BLOCK_OVERHEAD + size, // total incl. overhead
mmInfo: {
tags: mmTagsToString[mmInfo & 3],
size: size // as stored excl. overhead
},
gcInfo: {
color: gcColorToString[gcInfo & 3],
next: gcInfo & ~3,
prev: gcInfo2
},
rtId,
rtSize
};
}
/** Checks if rtrace is active, i.e. at least one event has occurred. */
get active() {
return Boolean(this.allocCount || this.resizeCount || this.moveCount || this.freeCount);
}
/** Checks if there are any leaks and emits them via `oninfo`. Returns the number of live blocks. */
check() {
if (this.oninfo) {
for (let [ptr, info] of this.blocks) {
this.oninfo("LIVE " + ptr + "\n" + info.allocStack.join("\n"));
}
}
return this.blocks.size;
}
// Runtime instrumentation
oninit(heapBase) {
this.heapBase = heapBase;
this.gcProfileStart = 0;
this.gcProfile.length = 0;
this.oninfo("INIT heapBase=" + heapBase);
}
onalloc(ptr) {
this.syncShadow();
++this.allocCount;
let info = this.getBlockInfo(ptr);
if (this.blocks.has(ptr)) {
this.onerror(Error("duplicate alloc: " + ptr), info);
} else {
this.oninfo("ALLOC " + ptr + ".." + (ptr + info.size));
this.markShadow(info);
let allocStack = trimStacktrace(new Error().stack, 1); // strip onalloc
this.blocks.set(ptr, Object.assign(info, { allocStack }));
}
}
onresize(ptr, oldSize) {
this.syncShadow();
++this.resizeCount;
const info = this.getBlockInfo(ptr);
if (!this.blocks.has(ptr)) {
this.onerror(Error("orphaned resize: " + ptr), info);
} else {
const beforeInfo = this.blocks.get(ptr);
if (beforeInfo.size != oldSize) {
this.onerror(Error(`size mismatch upon resize: ${ptr} (${beforeInfo.size} != ${oldSize})`), info);
}
const newSize = info.size;
this.oninfo("RESIZE " + ptr + ".." + (ptr + newSize) + " (" + oldSize + "->" + newSize + ")");
this.blocks.set(ptr, Object.assign(info, { allocStack: beforeInfo.allocStack }));
if (newSize > oldSize) {
this.markShadow(info, oldSize);
} else if (newSize < oldSize) {
this.unmarkShadow(info, oldSize);
}
}
}
onmove(oldPtr, newPtr) {
this.syncShadow();
++this.moveCount;
let oldInfo = this.getBlockInfo(oldPtr);
let newInfo = this.getBlockInfo(newPtr);
if (!this.blocks.has(oldPtr)) {
this.onerror(Error("orphaned move (old): " + oldPtr), oldInfo);
} else {
if (!this.blocks.has(newPtr)) {
this.onerror(Error("orphaned move (new): " + newPtr), newInfo);
} else {
const beforeInfo = this.blocks.get(oldPtr);
const oldSize = oldInfo.size;
const newSize = newInfo.size;
if (beforeInfo.size != oldSize) {
this.onerror(Error(`size mismatch upon move: ${oldPtr} (${beforeInfo.size} != ${oldSize})`), oldInfo);
}
this.oninfo("MOVE " + oldPtr + ".." + (oldPtr + oldSize) + " -> " + newPtr + ".." + (newPtr + newSize));
// calls new alloc before and old free after
}
}
}
onvisit(ptr) {
// Indicates that a block has been freed but it still visited by the GC
if (ptr > this.heapBase && !this.blocks.has(ptr)) {
let err = Error("orphaned visit: " + ptr);
let info = this.freedBlocks.get(ptr);
if (info) {
err.stack += "\n^ allocated at:\n" + info.allocStack.join("\n");
err.stack += "\n^ freed at:\n" + info.freeStack.join("\n");
}
this.onerror(err, null);
return false;
}
return true;
}
onfree(ptr) {
this.syncShadow();
++this.freeCount;
let info = this.getBlockInfo(ptr);
if (!this.blocks.has(ptr)) {
this.onerror(Error("orphaned free: " + ptr), info);
} else {
const oldInfo = this.blocks.get(ptr);
if (info.size != oldInfo.size) {
this.onerror(Error(`size mismatch upon free: ${ptr} (${oldInfo.size} != ${info.size})`), info);
}
this.oninfo("FREE " + ptr + ".." + (ptr + info.size));
this.unmarkShadow(info);
const allocInfo = this.blocks.get(ptr);
this.blocks.delete(ptr);
const allocStack = allocInfo.allocStack;
const freeStack = trimStacktrace(new Error().stack, 1); // strip onfree
// (not much) TODO: Maintaining these is essentially a memory leak
this.freedBlocks.set(ptr, { allocStack, freeStack });
}
}
oncollect(total) {
this.oninfo(`COLLECT at ${total}`);
this.plot(total);
this.oncollect_();
}
// GC profiling
plot(total, pause = 0) {
if (!this.gcProfileStart) this.gcProfileStart = Date.now();
this.gcProfile.push([ Date.now() - this.gcProfileStart, total, pause ]);
}
oninterrupt(total) {
this.interruptStart = hrtime();
this.plot(total);
}
onyield(total) {
let pause = hrtime() - this.interruptStart;
if (pause >= 1) console.log("interrupted for " + pause.toFixed(1) + "ms");
this.plot(total, pause);
}
// Memory instrumentation
onstore(ptr, offset, bytes, isRT) {
this.accessShadow(ptr + offset, bytes, false, isRT);
return ptr;
}
onload(ptr, offset, bytes, isRT) {
this.accessShadow(ptr + offset, bytes, true, isRT);
return ptr;
}
}
export default {
Rtrace
};