-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhprof.ts
More file actions
1225 lines (1072 loc) · 47.7 KB
/
Copy pathhprof.ts
File metadata and controls
1225 lines (1072 loc) · 47.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ─── Enums & Constants ───────────────────────────────────────────────────────
// NOTE: parseHprof is intentionally synchronous and CPU-heavy.
// Call it from a Web Worker (see hprof.worker.ts) so the UI stays responsive.
export const Type = {
OBJECT: 0, BOOLEAN: 1, CHAR: 2, FLOAT: 3, DOUBLE: 4,
BYTE: 5, SHORT: 6, INT: 7, LONG: 8,
} as const;
export type TypeId = (typeof Type)[keyof typeof Type];
export const TypeName: Record<number, string> = {
0: "Object", 1: "boolean", 2: "char", 3: "float", 4: "double",
5: "byte", 6: "short", 7: "int", 8: "long",
};
const TypeSize = [0, 1, 2, 4, 8, 1, 2, 4, 8];
function typeSize(t: number, idSize: number): number {
return t === Type.OBJECT ? idSize : TypeSize[t];
}
export const Reachability = {
STRONG: 0, SOFT: 1, FINALIZER: 2, WEAK: 3, PHANTOM: 4, UNREACHABLE: 5,
} as const;
export const ReachabilityName: Record<number, string> = {
0: "strong", 1: "soft", 2: "finalizer", 3: "weak", 4: "phantom", 5: "unreachable",
};
export const RootTypeNames = [
"JNI_GLOBAL", "JNI_LOCAL", "JAVA_FRAME", "NATIVE_STACK", "STICKY_CLASS",
"THREAD_BLOCK", "MONITOR", "THREAD", "INTERNED_STRING", "DEBUGGER",
"VM_INTERNAL", "UNKNOWN", "JNI_MONITOR", "FINALIZING",
];
const HPROF_TYPES: (number | null)[] = [
null, null, Type.OBJECT, null,
Type.BOOLEAN, Type.CHAR, Type.FLOAT, Type.DOUBLE,
Type.BYTE, Type.SHORT, Type.INT, Type.LONG,
];
// ─── Size ────────────────────────────────────────────────────────────────────
export class Size {
constructor(public java: number = 0, public native_: number = 0) {}
get total(): number { return this.java + this.native_; }
plus(o: Size): Size { return new Size(this.java + o.java, this.native_ + o.native_); }
isZero(): boolean { return this.java === 0 && this.native_ === 0; }
}
export const ZERO_SIZE = new Size(0, 0);
// ─── HprofBuffer ─────────────────────────────────────────────────────────────
class HprofBuffer {
private view: DataView;
private pos = 0;
private idSize8 = false;
constructor(private buf: ArrayBuffer) {
this.view = new DataView(buf);
}
setIdSize8() { this.idSize8 = true; }
hasRemaining(): boolean { return this.pos < this.buf.byteLength; }
size(): number { return this.buf.byteLength; }
tell(): number { return this.pos; }
seek(p: number) { this.pos = p; }
skip(n: number) { this.pos += n; }
getU1(): number { const v = this.view.getUint8(this.pos); this.pos += 1; return v; }
getU2(): number { const v = this.view.getUint16(this.pos); this.pos += 2; return v; }
getU4(): number { const v = this.view.getInt32(this.pos); this.pos += 4; return v; }
getU4Unsigned(): number { const v = this.view.getUint32(this.pos); this.pos += 4; return v; }
getId(): number {
if (this.idSize8) {
const hi = this.view.getUint32(this.pos);
const lo = this.view.getUint32(this.pos + 4);
this.pos += 8;
return hi * 0x100000000 + lo;
}
const v = this.view.getUint32(this.pos);
this.pos += 4;
return v;
}
getBool(): boolean { return this.getU1() !== 0; }
getChar(): string { const v = this.view.getUint16(this.pos); this.pos += 2; return String.fromCharCode(v); }
getFloat(): number { const v = this.view.getFloat32(this.pos); this.pos += 4; return v; }
getDouble(): number { const v = this.view.getFloat64(this.pos); this.pos += 8; return v; }
getByte(): number { const v = this.view.getInt8(this.pos); this.pos += 1; return v; }
getShort(): number { const v = this.view.getInt16(this.pos); this.pos += 2; return v; }
getInt(): number { const v = this.view.getInt32(this.pos); this.pos += 4; return v; }
getLong(): number {
const hi = this.view.getInt32(this.pos);
const lo = this.view.getUint32(this.pos + 4);
this.pos += 8;
return hi * 0x100000000 + lo;
}
getBytes(n: number): Uint8Array {
const arr = new Uint8Array(this.buf, this.pos, n);
this.pos += n;
return arr;
}
getType(): number {
const id = this.getU1();
if (id >= HPROF_TYPES.length || HPROF_TYPES[id] === null) throw new Error("Invalid type id: " + id);
return HPROF_TYPES[id]!;
}
getPrimitiveType(): number {
const t = this.getType();
if (t === Type.OBJECT) throw new Error("Expected primitive type, got Object");
return t;
}
}
// ─── Field descriptors ───────────────────────────────────────────────────────
export interface Field {
name: string;
type: number;
}
export interface FieldValue {
name: string;
type: number;
value: any;
}
interface Reference {
src: AhatInstance;
field: string;
ref: AhatInstance;
reachability: number;
}
// ─── Heap ────────────────────────────────────────────────────────────────────
export class AhatHeap {
public size: Size = ZERO_SIZE;
public baseline: AhatHeap = this;
constructor(public name: string, public index: number) {}
addToSize(s: Size) { this.size = this.size.plus(s); }
getBaseline(): AhatHeap { return this.baseline; }
}
// ─── Instance hierarchy ──────────────────────────────────────────────────────
export class AhatInstance {
public heap: AhatHeap | null = null;
public classObj: AhatClassObj | null = null;
public site: SiteNode | null = null;
public rootTypes = 0;
public registeredNativeSize = 0;
public reachability: number = Reachability.UNREACHABLE;
public nextToGcRoot: AhatInstance | null = null;
public nextToGcRootField = "";
public reverseRefs: AhatInstance[] = [];
public immediateDominator: AhatInstance | null = null;
public dominated: AhatInstance[] = [];
public retainedSizes: Size[] | null = null;
public baseline: AhatInstance = this;
public tempData: any = null;
constructor(public id: number) {}
init(heap: AhatHeap, site: SiteNode | null, classObj: AhatClassObj | null) {
this.heap = heap; this.site = site; this.classObj = classObj;
}
getSize(): Size {
const base = this.classObj ? this.classObj.instanceSize : 0;
return new Size(base + this.getExtraJavaSize(), this.registeredNativeSize);
}
getExtraJavaSize(): number { return 0; }
getRetainedSize(heap: AhatHeap): Size {
if (this.retainedSizes && heap.index >= 0 && heap.index < this.retainedSizes.length)
return this.retainedSizes[heap.index];
return ZERO_SIZE;
}
getTotalRetainedSize(): Size {
if (!this.retainedSizes) return ZERO_SIZE;
let s = ZERO_SIZE;
for (const rs of this.retainedSizes) s = s.plus(rs);
return s;
}
isRoot(): boolean { return this.rootTypes !== 0; }
addRootType(mask: number) { this.rootTypes |= mask; }
getRootTypeNames(): string[] | null {
if (!this.isRoot()) return null;
const names: string[] = [];
for (let i = 0; i < 14; i++) if (this.rootTypes & (1 << i)) names.push(RootTypeNames[i]);
return names;
}
getClassName(): string { return this.classObj ? this.classObj.className : "???"; }
isInstanceOfClass(name: string): boolean {
let cls = this.classObj;
while (cls) { if (cls.className === name) return true; cls = cls.superClassObj; }
return false;
}
isClassObj(): boolean { return false; }
isArrayInstance(): boolean { return false; }
isClassInstance(): boolean { return false; }
asClassObj(): AhatClassObj | null { return null; }
asArrayInstance(): AhatArrayInstance | null { return null; }
asClassInstance(): AhatClassInstance | null { return null; }
getReferences(): Reference[] { return []; }
getField(_name: string): any { return undefined; }
getRefField(_name: string): AhatInstance | undefined { return undefined; }
asString(_maxChars?: number): string | null { return null; }
getReferent(): AhatInstance | null { return null; }
getPathFromGcRoot(): { instance: AhatInstance; field: string; isDominator: boolean }[] | null {
if (this.reachability === Reachability.UNREACHABLE) return null;
const path: { instance: AhatInstance; field: string; isDominator: boolean }[] = [];
let inst: AhatInstance | null = this;
while (inst) {
path.push({ instance: inst, field: "", isDominator: false });
if (inst.isRoot() || !inst.nextToGcRoot) break;
path[path.length - 1].field = inst.nextToGcRootField;
inst = inst.nextToGcRoot;
}
let dom: AhatInstance | null = this;
for (let i = 0; i < path.length; i++) {
if (path[i].instance === dom) {
path[i].isDominator = true;
dom = dom.immediateDominator;
}
}
path.reverse();
return path;
}
toString(): string {
return `${this.getClassName()}@${this.id.toString(16).padStart(8, "0")}`;
}
}
export class AhatClassInstance extends AhatInstance {
private fields: any[] = [];
isClassInstance() { return true; }
asClassInstance() { return this; }
getExtraJavaSize() { return 0; }
initFields(values: any[]) { this.fields = values; }
*getInstanceFields(): Generator<FieldValue> {
let cls = this.classObj;
let idx = 0;
while (cls) {
for (const f of cls.instanceFields) {
yield { name: f.name, type: f.type, value: this.fields[idx++] };
}
cls = cls.superClassObj;
}
}
getField(name: string): any {
for (const f of this.getInstanceFields()) if (f.name === name) return f.value;
return undefined;
}
getRefField(name: string): AhatInstance | undefined {
const v = this.getField(name);
return (v instanceof AhatInstance) ? v : undefined;
}
getReferences(): Reference[] {
const refs: Reference[] = [];
const refType = this._getJavaLangRefType();
for (const f of this.getInstanceFields()) {
if (f.value instanceof AhatInstance) {
const reach: number = (refType !== Reachability.STRONG && f.name === "referent") ? refType : Reachability.STRONG;
refs.push({ src: this, field: "." + f.name, ref: f.value, reachability: reach as any });
}
}
return refs;
}
private _getJavaLangRefType(): number {
let cls = this.classObj;
while (cls) {
switch (cls.className) {
case "java.lang.ref.PhantomReference": return Reachability.PHANTOM;
case "java.lang.ref.WeakReference": return Reachability.WEAK;
case "java.lang.ref.FinalizerReference":
case "java.lang.ref.Finalizer": return Reachability.FINALIZER;
case "java.lang.ref.SoftReference": return Reachability.SOFT;
}
cls = cls.superClassObj;
}
return Reachability.STRONG;
}
getReferent(): AhatInstance | null {
if (this.isInstanceOfClass("java.lang.ref.Reference")) return this.getRefField("referent") ?? null;
return null;
}
asString(maxChars = -1): string | null {
if (!this.isInstanceOfClass("java.lang.String")) return null;
const val = this.getField("value");
if (!(val instanceof AhatInstance) || !val.isArrayInstance()) return null;
const arr = val.asArrayInstance()!;
const count = (() => { const v = this.getField("count"); return typeof v === "number" ? v : arr.length; })();
const offset = (() => { const v = this.getField("offset"); return typeof v === "number" ? v : 0; })();
return arr.asStringSlice(offset, count, maxChars);
}
toString(): string {
return `${this.getClassName()}@${this.id.toString(16).padStart(8, "0")}`;
}
}
export class AhatArrayInstance extends AhatInstance {
public values: any[] = [];
public elemType: number = Type.OBJECT;
constructor(id: number, public refSize: number) { super(id); }
isArrayInstance() { return true; }
asArrayInstance() { return this; }
get length() { return this.values.length; }
getExtraJavaSize(): number {
if (this.values.length === 0) return 0;
return typeSize(this.elemType, this.refSize) * this.values.length;
}
initPrimitive(type: number, data: any[]) { this.elemType = type; this.values = data; }
initObjects(objects: (AhatInstance | null)[]) { this.elemType = Type.OBJECT; this.values = objects; }
getReferences(): Reference[] {
if (this.elemType !== Type.OBJECT) return [];
const refs: Reference[] = [];
for (let i = 0; i < this.values.length; i++) {
if (this.values[i] instanceof AhatInstance) {
refs.push({ src: this, field: `[${i}]`, ref: this.values[i], reachability: Reachability.STRONG });
}
}
return refs;
}
asString(maxChars = -1): string | null {
return this.asStringSlice(0, this.length, maxChars);
}
asStringSlice(offset: number, count: number, maxChars: number): string | null {
if (this.elemType === Type.CHAR) {
if (maxChars >= 0 && maxChars < count) count = maxChars;
let s = "";
for (let i = offset; i < offset + count && i < this.values.length; i++) s += this.values[i];
return s;
}
if (this.elemType === Type.BYTE) {
if (maxChars >= 0 && maxChars < count) count = maxChars;
let s = "";
for (let i = offset; i < offset + count && i < this.values.length; i++)
s += String.fromCharCode(this.values[i] & 0xFF);
return s;
}
return null;
}
toString(): string {
let cn = this.getClassName();
if (cn.endsWith("[]")) cn = cn.slice(0, -2);
return `${cn}[${this.values.length}]@${this.id.toString(16).padStart(8, "0")}`;
}
}
export class AhatClassObj extends AhatInstance {
public superClassObj: AhatClassObj | null = null;
public classLoader: AhatInstance | null = null;
public staticFieldValues: FieldValue[] = [];
public instanceFields: Field[] = [];
public staticFieldsSize = 0;
public instanceSize = 0;
constructor(id: number, public className: string) { super(id); }
isClassObj() { return true; }
asClassObj() { return this; }
getExtraJavaSize() { return this.staticFieldsSize; }
getName() { return this.className; }
getClassName() { return "java.lang.Class"; }
getReferences(): Reference[] {
const refs: Reference[] = [];
for (const f of this.staticFieldValues) {
if (f.value instanceof AhatInstance) {
refs.push({ src: this, field: "." + f.name, ref: f.value, reachability: Reachability.STRONG });
}
}
return refs;
}
toString() { return `class ${this.className}`; }
}
export class SuperRoot extends AhatInstance {
public roots: AhatInstance[] = [];
constructor() { super(0); }
addRoot(inst: AhatInstance) { this.roots.push(inst); }
getExtraJavaSize() { return 0; }
getReferences(): Reference[] {
return this.roots.map((r, i) => ({
src: this as AhatInstance, field: `.roots[${i}]`, ref: r, reachability: Reachability.STRONG,
}));
}
}
// ─── Site ────────────────────────────────────────────────────────────────────
export interface ObjectsInfo {
heap: AhatHeap;
classObj: AhatClassObj | null;
numInstances: number;
numBytes: Size;
baseline: ObjectsInfo;
getClassName(): string;
}
interface StackFrame {
method: string;
signature: string;
filename: string;
line: number;
}
export class SiteNode {
public id = -1;
public children: SiteNode[] = [];
public objects: AhatInstance[] = [];
public objectsInfos: ObjectsInfo[] = [];
private objectsInfoMap = new Map<string, ObjectsInfo>();
public sizesByHeap: Size[] | null = null;
public baseline: SiteNode = this;
constructor(
public parent: SiteNode | null,
public method: string,
public signature: string,
public filename: string,
public line: number,
) {}
getSite(frames: StackFrame[]): SiteNode {
if (!frames) return this;
let site: SiteNode = this;
for (let s = frames.length - 1; s >= 0; s--) {
const f = frames[s];
let child: SiteNode | null = null;
for (const c of site.children) {
if (c.line === f.line && c.method === f.method && c.signature === f.signature && c.filename === f.filename) {
child = c; break;
}
}
if (!child) {
child = new SiteNode(site, f.method, f.signature, f.filename, f.line);
site.children.push(child);
}
site = child;
}
return site;
}
addInstance(inst: AhatInstance) { this.objects.push(inst); }
prepareForUse(id: number, numHeaps: number, retained: number): number {
this.id = id++;
this.sizesByHeap = new Array(numHeaps).fill(null).map(() => ZERO_SIZE);
for (const inst of this.objects) {
if (inst.reachability <= retained) {
const heap = inst.heap!;
const size = inst.getSize();
const info = this.getObjectsInfo(heap, inst.classObj);
info.numInstances++;
info.numBytes = info.numBytes.plus(size);
this.sizesByHeap[heap.index] = this.sizesByHeap[heap.index].plus(size);
}
}
for (const child of this.children) {
id = child.prepareForUse(id, numHeaps, retained);
for (const ci of child.objectsInfos) {
const info = this.getObjectsInfo(ci.heap, ci.classObj);
info.numInstances += ci.numInstances;
info.numBytes = info.numBytes.plus(ci.numBytes);
}
if (child.sizesByHeap) {
for (let i = 0; i < numHeaps; i++) {
this.sizesByHeap[i] = this.sizesByHeap[i].plus(child.sizesByHeap[i]);
}
}
}
return id;
}
getObjectsInfo(heap: AhatHeap, classObj: AhatClassObj | null): ObjectsInfo {
const key = `${heap.index}:${classObj ? classObj.id : 0}`;
let info = this.objectsInfoMap.get(key);
if (!info) {
info = {
heap, classObj, numInstances: 0, numBytes: ZERO_SIZE,
getClassName() { return this.classObj ? this.classObj.className : "???"; },
baseline: null!,
};
info.baseline = info;
this.objectsInfos.push(info);
this.objectsInfoMap.set(key, info);
}
return info;
}
getSizeForHeap(heap: AhatHeap): Size { return this.sizesByHeap ? this.sizesByHeap[heap.index] : ZERO_SIZE; }
getTotalSize(): Size {
if (!this.sizesByHeap) return ZERO_SIZE;
return this.sizesByHeap.reduce((a, b) => a.plus(b), ZERO_SIZE);
}
findSite(id: number): SiteNode | null {
if (id === this.id) return this;
let start = 0, end = this.children.length;
while (start < end) {
const mid = start + ((end - start) >> 1);
const midSite = this.children[mid];
if (id < midSite.id) { end = mid; }
else if (mid + 1 === end) { return midSite.findSite(id); }
else if (id < this.children[mid + 1].id) { return midSite.findSite(id); }
else { start = mid + 1; }
}
return null;
}
getObjects(predicate: (i: AhatInstance) => boolean, consumer: (i: AhatInstance) => void) {
for (const inst of this.objects) if (predicate(inst)) consumer(inst);
for (const child of this.children) child.getObjects(predicate, consumer);
}
}
// ─── Snapshot ────────────────────────────────────────────────────────────────
export class AhatSnapshot {
constructor(
public superRoot: SuperRoot,
public instances: Map<number, AhatInstance>,
public heaps: AhatHeap[],
public rootSite: SiteNode,
) {}
findInstance(id: number): AhatInstance | null { return this.instances.get(id) ?? null; }
getRooted(): AhatInstance[] { return this.superRoot.dominated; }
getSite(id: number): SiteNode { return this.rootSite.findSite(id) ?? this.rootSite; }
getHeap(name: string): AhatHeap | null { return this.heaps.find(h => h.name === name) ?? null; }
}
// ─── normalizeClassName ──────────────────────────────────────────────────────
function normalizeClassName(name: string): string {
let numDim = 0;
while (name.startsWith("[")) { numDim++; name = name.substring(1); }
if (numDim > 0) {
switch (name.charAt(0)) {
case 'Z': name = "boolean"; break; case 'B': name = "byte"; break;
case 'C': name = "char"; break; case 'S': name = "short"; break;
case 'I': name = "int"; break; case 'J': name = "long"; break;
case 'F': name = "float"; break; case 'D': name = "double"; break;
case 'L': name = name.substring(1, name.length - 1); break;
default: throw new Error("Invalid type sig in class name: " + name);
}
}
name = name.replace(/\//g, ".");
for (let i = 0; i < numDim; i++) name += "[]";
return name;
}
// ─── Dominators ──────────────────────────────────────────────────────────────
// Dominator approximation via BFS spanning tree.
//
// Full dominator computation (e.g. Cooper-Harvey-Kennedy) requires O(N·E·depth)
// work which is intractable for large Android heap dumps (500K+ objects).
//
// Instead we use a simple BFS from the root: the first time we reach a node,
// its BFS parent is its approximate immediate dominator. For spanning-tree
// edges this is exact; for back/cross edges it over-approximates (a node may
// appear to retain more than it truly does), but that is acceptable for a heap
// analysis viewer and is exactly what the original ahat Java tool does.
//
// The result is computed in a single O(N + E) pass — fast enough for any
// real-world heap dump.
function computeDominators(
root: AhatInstance,
getRefs: (node: AhatInstance) => AhatInstance[],
setDominator: (node: AhatInstance, dominator: AhatInstance) => void,
) {
const visited = new Set<AhatInstance>();
visited.add(root);
const queue: AhatInstance[] = [root];
let head = 0;
while (head < queue.length) {
const node = queue[head++];
for (const child of getRefs(node)) {
if (!visited.has(child)) {
visited.add(child);
setDominator(child, node);
queue.push(child);
}
}
}
}
// ─── Parser helpers ──────────────────────────────────────────────────────────
function readDeferredValue(hprof: HprofBuffer, type: number): any {
switch (type) {
case Type.OBJECT: return { _deferred: true, id: hprof.getId() };
case Type.BOOLEAN: return hprof.getBool();
case Type.CHAR: return hprof.getChar();
case Type.FLOAT: return hprof.getFloat();
case Type.DOUBLE: return hprof.getDouble();
case Type.BYTE: return hprof.getByte();
case Type.SHORT: return hprof.getShort();
case Type.INT: return hprof.getInt();
case Type.LONG: return hprof.getLong();
}
}
function readValue(hprof: HprofBuffer, type: number, instances: Map<number, AhatInstance>): any {
switch (type) {
case Type.OBJECT: return instances.get(hprof.getId()) ?? null;
case Type.BOOLEAN: return hprof.getBool();
case Type.CHAR: return hprof.getChar();
case Type.FLOAT: return hprof.getFloat();
case Type.DOUBLE: return hprof.getDouble();
case Type.BYTE: return hprof.getByte();
case Type.SHORT: return hprof.getShort();
case Type.INT: return hprof.getInt();
case Type.LONG: return hprof.getLong();
}
}
function readPrimitiveArray(hprof: HprofBuffer, type: number, length: number): any[] {
const a: any[] = new Array(length);
switch (type) {
case Type.BOOLEAN: for (let i = 0; i < length; i++) a[i] = hprof.getBool(); break;
case Type.CHAR: for (let i = 0; i < length; i++) a[i] = hprof.getChar(); break;
case Type.FLOAT: for (let i = 0; i < length; i++) a[i] = hprof.getFloat(); break;
case Type.DOUBLE: for (let i = 0; i < length; i++) a[i] = hprof.getDouble(); break;
case Type.BYTE: for (let i = 0; i < length; i++) a[i] = hprof.getByte(); break;
case Type.SHORT: for (let i = 0; i < length; i++) a[i] = hprof.getShort(); break;
case Type.INT: for (let i = 0; i < length; i++) a[i] = hprof.getInt(); break;
case Type.LONG: for (let i = 0; i < length; i++) a[i] = hprof.getLong(); break;
default: throw new Error("Unsupported primitive type: " + type);
}
return a;
}
// ─── Main Parser ─────────────────────────────────────────────────────────────
export type ProgressCallback = (msg: string, pct: number) => void;
export function parseHprof(buffer: ArrayBuffer, onProgress?: ProgressCallback): AhatSnapshot {
const hprof = new HprofBuffer(buffer);
let idSizeVal: number;
// Read header
let b: number;
while ((b = hprof.getU1()) !== 0) { /* consume format string */ }
idSizeVal = hprof.getU4();
if (idSizeVal === 8) hprof.setIdSize8();
else if (idSizeVal !== 4) throw new Error("Unsupported id size: " + idSizeVal);
hprof.getU4(); hprof.getU4(); // timestamps
const rootSite = new SiteNode(null, "ROOT", "", "", 0);
const instances: AhatInstance[] = [];
const roots: { id: number; type: number }[] = [];
// Heap management
const heapsList: AhatHeap[] = [];
let currentHeap: AhatHeap | null = null;
function getCurrentHeap(): AhatHeap {
if (!currentHeap) setCurrentHeap("default");
return currentHeap!;
}
function setCurrentHeap(name: string) {
for (const h of heapsList) if (h.name === name) { currentHeap = h; return; }
currentHeap = new AhatHeap(name, heapsList.length);
heapsList.push(currentHeap);
}
const strings = new Map<number, string>(); strings.set(0, "???");
const frames = new Map<number, StackFrame>();
const sites = new Map<number, SiteNode>();
const classNamesBySerial = new Map<number, string>();
let javaLangClass: AhatClassObj | null = null;
const primArrayClasses: (AhatClassObj | null)[] = new Array(9).fill(null);
const classes: AhatClassObj[] = [];
let classById: Map<number, AhatClassObj> | null = null;
onProgress?.("Reading HPROF file...", 0);
const totalSize = hprof.size();
let lastPct = 0;
while (hprof.hasRemaining()) {
const pct = Math.floor((hprof.tell() / totalSize) * 100);
if (pct > lastPct + 4) { onProgress?.("Reading HPROF...", pct); lastPct = pct; }
const tag = hprof.getU1();
hprof.getU4(); // time
const recordLength = hprof.getU4Unsigned();
switch (tag) {
case 0x01: { // STRING
const sid = hprof.getId();
const bytes = hprof.getBytes(recordLength - idSizeVal);
strings.set(sid, new TextDecoder().decode(bytes));
break;
}
case 0x02: { // LOAD CLASS
const serial = hprof.getU4(); const objId = hprof.getId();
hprof.getU4(); const nameId = hprof.getId();
const className = normalizeClassName(strings.get(nameId) || "???");
const classObj = new AhatClassObj(objId, className);
classNamesBySerial.set(serial, className);
classes.push(classObj);
if (className === "java.lang.Class") javaLangClass = classObj;
const tn = ["boolean[]","char[]","float[]","double[]","byte[]","short[]","int[]","long[]"];
const tv = [Type.BOOLEAN,Type.CHAR,Type.FLOAT,Type.DOUBLE,Type.BYTE,Type.SHORT,Type.INT,Type.LONG];
for (let i = 0; i < tn.length; i++) if (className === tn[i]) primArrayClasses[tv[i]] = classObj;
break;
}
case 0x04: { // STACK FRAME
const fid = hprof.getId();
const mn = hprof.getId(); const ms = hprof.getId(); const fn = hprof.getId();
const cs = hprof.getU4(); const ln = hprof.getU4();
frames.set(fid, { method: strings.get(mn)||"???", signature: strings.get(ms)||"", filename: strings.get(fn)||"???", line: ln });
break;
}
case 0x05: { // STACK TRACE
const ss = hprof.getU4(); hprof.getU4(); const nf = hprof.getU4();
const trace: StackFrame[] = [];
for (let i = 0; i < nf; i++) { const f = frames.get(hprof.getId()); if (f) trace.push(f); }
sites.set(ss, rootSite.getSite(trace));
break;
}
case 0x0C: case 0x1C: { // HEAP DUMP / SEGMENT
const end = hprof.tell() + recordLength;
if (!classById) { classById = new Map(); for (const c of classes) classById.set(c.id, c); }
while (hprof.tell() < end) {
const st = hprof.getU1();
switch (st) {
case 0x01: { const o=hprof.getId(); hprof.getId(); roots.push({id:o,type:1<<0}); break; }
case 0x02: { const o=hprof.getId(); hprof.getU4(); hprof.getU4(); roots.push({id:o,type:1<<1}); break; }
case 0x03: { const o=hprof.getId(); hprof.getU4(); hprof.getU4(); roots.push({id:o,type:1<<2}); break; }
case 0x04: { const o=hprof.getId(); hprof.getU4(); roots.push({id:o,type:1<<3}); break; }
case 0x05: { roots.push({id:hprof.getId(),type:1<<4}); break; }
case 0x06: { const o=hprof.getId(); hprof.getU4(); roots.push({id:o,type:1<<5}); break; }
case 0x07: { roots.push({id:hprof.getId(),type:1<<6}); break; }
case 0x08: { const o=hprof.getId(); hprof.getU4(); hprof.getU4(); roots.push({id:o,type:1<<7}); break; }
case 0x20: { // CLASS DUMP
const oid=hprof.getId(); const ss=hprof.getU4(); const superId=hprof.getId();
const clId=hprof.getId(); hprof.getId(); hprof.getId(); hprof.getId(); hprof.getId();
const is_=hprof.getU4(); const cps=hprof.getU2();
for(let i=0;i<cps;i++){hprof.getU2();const t=hprof.getType();hprof.skip(typeSize(t,idSizeVal));}
const ns=hprof.getU2(); const sfs:FieldValue[]=[]; const obj=classById!.get(oid); let sfz=0;
for(let i=0;i<ns;i++){
const fn=strings.get(hprof.getId())||"???"; const t=hprof.getType();
const v=readDeferredValue(hprof,t); sfz+=typeSize(t,idSizeVal);
sfs.push({name:fn,type:t,value:v});
}
const sup=classById!.get(superId)||null; const ni=hprof.getU2(); const ifs:Field[]=[];
for(let i=0;i<ni;i++) ifs.push({name:strings.get(hprof.getId())||"???",type:hprof.getType()});
const site=sites.get(ss)||rootSite;
if(obj && javaLangClass){
obj.init(getCurrentHeap(),site,javaLangClass);
obj.superClassObj=sup; obj.instanceSize=is_; obj.instanceFields=ifs; obj.staticFieldsSize=sfz;
obj.tempData={classLoaderId:clId,staticFields:sfs};
}
break;
}
case 0x21: { // INSTANCE DUMP
const oid=hprof.getId(); const ss=hprof.getU4(); const cid=hprof.getId(); const nb=hprof.getU4();
const pos=hprof.tell(); hprof.skip(nb);
const o=new AhatClassInstance(oid);
o.init(getCurrentHeap(),sites.get(ss)||rootSite,classById!.get(cid)||null);
o.tempData={position:pos}; instances.push(o);
break;
}
case 0x22: { // OBJ ARRAY
const oid=hprof.getId(); const ss=hprof.getU4(); const len=hprof.getU4(); const cid=hprof.getId();
const pos=hprof.tell(); hprof.skip(len*idSizeVal);
const o=new AhatArrayInstance(oid,idSizeVal);
o.init(getCurrentHeap(),sites.get(ss)||rootSite,classById!.get(cid)||null);
o.tempData={length:len,position:pos}; instances.push(o);
break;
}
case 0x23: { // PRIM ARRAY
const oid=hprof.getId(); const ss=hprof.getU4(); const len=hprof.getU4(); const type=hprof.getPrimitiveType();
const pc=primArrayClasses[type]; if(!pc) throw new Error("No class for "+TypeName[type]+"[]");
const o=new AhatArrayInstance(oid,idSizeVal);
o.init(getCurrentHeap(),sites.get(ss)||rootSite,pc);
o.initPrimitive(type,readPrimitiveArray(hprof,type,len)); instances.push(o);
break;
}
case 0x89: { roots.push({id:hprof.getId(),type:1<<8}); break; }
case 0x8a: { roots.push({id:hprof.getId(),type:1<<13}); break; }
case 0x8b: { roots.push({id:hprof.getId(),type:1<<9}); break; }
case 0x8d: { roots.push({id:hprof.getId(),type:1<<10}); break; }
case 0x8e: { const o=hprof.getId(); hprof.getU4(); hprof.getU4(); roots.push({id:o,type:1<<12}); break; }
case 0xfe: { hprof.getU4(); const si=hprof.getId(); setCurrentHeap(strings.get(si)||"default"); break; }
case 0xff: { roots.push({id:hprof.getId(),type:1<<11}); break; }
default: throw new Error(`Unsupported heap sub tag 0x${st.toString(16)}`);
}
}
break;
}
default: hprof.skip(recordLength); break;
}
}
onProgress?.("Resolving references...", 50);
// Build instance map
const allInst = [...instances, ...classes];
const instMap = new Map<number, AhatInstance>();
for (const i of allInst) instMap.set(i.id, i);
// Sort & process roots
roots.sort((a, b) => (a?.id ?? Infinity) - (b?.id ?? Infinity));
roots.push(null!);
const superRoot = new SuperRoot();
let ri = 0;
let root = roots[ri++];
const sorted = [...allInst].sort((a, b) => a.id - b.id);
for (const inst of sorted) {
while (root && root.id < inst.id) root = roots[ri++];
if (root && root.id === inst.id) {
superRoot.addRoot(inst);
while (root && root.id === inst.id) { inst.addRootType(root.type); root = roots[ri++]; }
}
if (inst instanceof AhatClassInstance && inst.tempData) {
const d = inst.tempData; inst.tempData = null;
const vals: any[] = [];
hprof.seek(d.position);
let cls = inst.classObj;
while (cls) {
for (const f of cls.instanceFields) vals.push(readValue(hprof, f.type, instMap));
cls = cls.superClassObj;
}
inst.initFields(vals);
} else if (inst instanceof AhatClassObj && inst.tempData) {
const d = inst.tempData; inst.tempData = null;
inst.classLoader = instMap.get(d.classLoaderId) ?? null;
for (const sf of d.staticFields) {
let val = sf.value;
if (val && typeof val === "object" && val._deferred) val = instMap.get(val.id) ?? null;
inst.staticFieldValues.push({ name: sf.name, type: sf.type, value: val });
}
} else if (inst instanceof AhatArrayInstance && inst.tempData) {
const d = inst.tempData; inst.tempData = null;
hprof.seek(d.position);
const arr: (AhatInstance | null)[] = new Array(d.length);
for (let i = 0; i < d.length; i++) arr[i] = instMap.get(hprof.getId()) ?? null;
inst.initObjects(arr);
}
}
onProgress?.("Computing reachability...", 60);
// Reachability BFS
const queues: Reference[][] = [];
for (let r = 0; r <= 5; r++) queues.push([]);
for (const ref of superRoot.getReferences()) queues[Reachability.STRONG].push(ref);
for (let reach = 0; reach <= 5; reach++) {
const q = queues[reach];
let qi = 0;
while (qi < q.length) {
const ref = q[qi++];
if (ref.ref.reachability === Reachability.UNREACHABLE) {
ref.ref.reachability = reach;
ref.ref.nextToGcRoot = ref.src;
ref.ref.nextToGcRootField = ref.field;
ref.ref.reverseRefs = [];
for (const cr of ref.ref.getReferences()) {
if (cr.reachability <= reach) q.push(cr);
else queues[cr.reachability].push(cr);
}
}
if (ref.src !== superRoot) ref.ref.reverseRefs.push(ref.src);
}
}
onProgress?.("Computing dominators...", 70);
const retained = Reachability.SOFT;
for (const i of allInst) if (i.site) i.site.addInstance(i);
computeDominators(
superRoot,
(node) => {
const refs = node.getReferences();
const result: AhatInstance[] = [];
for (const r of refs) if (r.reachability <= retained) result.push(r.ref);
return result;
},
(node, dominator) => { node.immediateDominator = dominator; dominator.dominated.push(node); },
);
onProgress?.("Computing retained sizes...", 85);
const numHeaps = heapsList.length;
const stack: AhatInstance[] = [superRoot];
while (stack.length > 0) {
const i = stack[stack.length - 1];
if (!i.retainedSizes) {
i.retainedSizes = new Array(numHeaps).fill(null).map(() => ZERO_SIZE);
if (!(i instanceof SuperRoot) && i.heap) {
i.retainedSizes[i.heap.index] = i.retainedSizes[i.heap.index].plus(i.getSize());
}
for (const d of i.dominated) stack.push(d);
} else {
stack.pop();
if (i.immediateDominator?.retainedSizes) {
for (let h = 0; h < numHeaps; h++) {
i.immediateDominator.retainedSizes[h] = i.immediateDominator.retainedSizes[h].plus(i.retainedSizes[h]);
}
}
}
}
for (const heap of heapsList) heap.addToSize(superRoot.getRetainedSize(heap));
rootSite.prepareForUse(0, numHeaps, retained);
onProgress?.("Done!", 100);
return new AhatSnapshot(superRoot, instMap, heapsList, rootSite);
}
// ─── Snapshot serialization ──────────────────────────────────────────────────
// Used to transfer an AhatSnapshot across a Worker boundary (postMessage).
// All inter-object references are replaced by numeric indices into a flat array.
export interface SerializedField { name: string; type: number; value: SerializedValue }
export type SerializedValue =
| { kind: "prim"; v: any }
| { kind: "ref"; idx: number } // index into the flat instances array
| { kind: "null" };
export interface SerializedSite {
method: string; signature: string; filename: string; line: number;
children: SerializedSite[];
// objectsInfos / sizesByHeap are recomputed on deserialize; objects are
// identified by instance index not stored here (they will be re-attached).
}
export interface SerializedInstance {
kind: "classObj" | "classInstance" | "arrayInstance";
id: number;
heapIdx: number;
siteId: number; // SiteNode.id (integer assigned during prepareForUse)
rootTypes: number;
reachability: number;
registeredNativeSize: number;
classObjIdx: number; // index in flat array, -1 if none
dominatedIdxs: number[];
immediateDominatorIdx: number; // -1 = superRoot, -2 = none
retainedSizes: [number, number][]; // [java, native] per heap
reverseRefIdxs: number[];
nextToGcRootIdx: number; // -1 = superRoot, -2 = none
nextToGcRootField: string;
// AhatClassObj specific
className?: string;
superClassObjIdx?: number; // -1 if none
instanceSize?: number;
instanceFields?: Field[];
staticFieldValues?: SerializedField[];
staticFieldsSize?: number;
// AhatClassInstance specific
fields?: SerializedValue[];
// AhatArrayInstance specific
elemType?: number;
values?: SerializedValue[];