hprof-analyzer 0.2.0

Fast, low-memory Java HPROF heap-dump analyzer with Eclipse MAT-parity reports (System Overview, Leak Suspects, Top Consumers).
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
//! Pass-2 low-level heap-record scanners + skip/reader helpers.

#![allow(dead_code)]

use std::io::{self, ErrorKind};

use crate::{
    reader::{HEAP_DUMP_END_KIND, HprofReader},
    types::{HprofType, heap, tags},
};

/// Subtract a consumed sub-record byte count from a heap-segment's `remaining`
/// counter, erroring instead of underflowing. A malformed or truncated
/// HEAP_DUMP_SEGMENT can declare a sub-record longer than the bytes actually
/// left in the segment; a plain `remaining -= n` would then wrap the `u64`
/// (panic in debug, a near-`u64::MAX` value in release that keeps the scan
/// loop spinning into out-of-bounds reads / total misparse of the stream).
/// Every scanner in this module routes its byte accounting through this.
#[inline]
pub(crate) fn sub_remaining(remaining: &mut u64, n: u64) -> io::Result<()> {
    *remaining = remaining
        .checked_sub(n)
        .ok_or_else(|| io::Error::new(ErrorKind::InvalidData, "heap segment sub-record overrun"))?;
    Ok(())
}

/// Full-file sequential scan invoking `f(addr, elem_bytes)` for each
/// PRIM_ARRAY_DUMP whose array address is in `wanted`. Only wanted arrays'
/// element bytes are materialized; everything else is skipped.
pub(crate) fn scan_prim_arrays<O, F>(
    open: O,
    id_size: u8,
    wanted: &std::collections::HashSet<u64>,
    mut f: F,
) -> io::Result<()>
where
    O: Fn() -> io::Result<HprofReader>,
    F: FnMut(u64, &[u8]),
{
    let ids = id_size as u64;
    let mut r = open()?;
    let mut scratch: Vec<u8> = Vec::with_capacity(256);
    loop {
        let (tag, length) = match r.next_record()? {
            None => break,
            Some(h) => h,
        };
        let result: io::Result<()> = (|| match tag {
            tags::HEAP_DUMP | tags::HEAP_DUMP_SEGMENT => {
                let mut remaining = length;
                while remaining > 0 {
                    let sub_tag = r.u1()?;
                    sub_remaining(&mut remaining, 1)?;
                    match sub_tag {
                        heap::ROOT_SYSTEM_CLASS
                        | heap::ROOT_UNKNOWN
                        | heap::ROOT_MONITOR_USED
                        | heap::ROOT_STICKY_CLASS
                        | heap::ROOT_INTERNED_STRING
                        | heap::ROOT_DEBUGGER
                        | heap::ROOT_VM_INTERNAL => {
                            r.skip(ids)?;
                            sub_remaining(&mut remaining, ids)?;
                        }
                        heap::ROOT_JNI_GLOBAL => {
                            r.skip(2 * ids)?;
                            sub_remaining(&mut remaining, 2 * ids)?;
                        }
                        heap::ROOT_JNI_LOCAL
                        | heap::ROOT_JAVA_FRAME
                        | heap::ROOT_JNI_MONITOR
                        | heap::ROOT_THREAD_OBJ => {
                            r.skip(ids + 8)?;
                            sub_remaining(&mut remaining, ids + 8)?;
                        }
                        heap::ROOT_NATIVE_STACK | heap::ROOT_THREAD_BLOCK => {
                            r.skip(ids + 4)?;
                            sub_remaining(&mut remaining, ids + 4)?;
                        }
                        heap::HEAP_DUMP_INFO => {
                            r.skip(4 + ids)?;
                            sub_remaining(&mut remaining, 4 + ids)?;
                        }
                        heap::CLASS_DUMP => {
                            let consumed = skip_class_dump(&mut r, id_size)?;
                            sub_remaining(&mut remaining, consumed)?;
                        }
                        heap::INSTANCE_DUMP => {
                            r.skip(ids + 4)?;
                            let _class_id = r.id()?;
                            let data_len = r.u4()? as u64;
                            r.skip(data_len)?;
                            sub_remaining(&mut remaining, ids + 4 + ids + 4 + data_len)?;
                        }
                        heap::OBJ_ARRAY_DUMP => {
                            r.skip(ids + 4)?;
                            let count = r.u4()? as u64;
                            r.skip(ids)?;
                            let byte_len = count.saturating_mul(ids);
                            r.skip(byte_len)?;
                            sub_remaining(&mut remaining, ids + 4 + 4 + ids + byte_len)?;
                        }
                        heap::PRIM_ARRAY_NODATA_DUMP => {
                            // Android ART: same header as PRIM_ARRAY_DUMP but no element data.
                            r.skip(ids + 4 + 4 + 1)?;
                            sub_remaining(&mut remaining, ids + 4 + 4 + 1)?;
                        }

                        heap::PRIM_ARRAY_DUMP => {
                            let addr = r.id()?;
                            r.skip(4)?;
                            let count = r.u4()? as u64;
                            let elem_type = r.u1()?;
                            let esz = HprofType::from_code(elem_type)
                                .map(|t| t.byte_size() as u64)
                                .unwrap_or(1);
                            let byte_len = count.saturating_mul(esz);
                            sub_remaining(&mut remaining, ids + 4 + 4 + 1 + byte_len)?;
                            if wanted.contains(&addr) {
                                r.read_bytes_reuse(&mut scratch, byte_len as usize)?;
                                f(addr, &scratch);
                            } else {
                                r.skip(byte_len)?;
                            }
                        }
                        other => {
                            return Err(io::Error::new(
                                ErrorKind::InvalidData,
                                format!("unknown heap sub-tag 0x{other:02x} in thread-name scan"),
                            ));
                        }
                    }
                }
                Ok(())
            }
            tags::HEAP_DUMP_END => Err(io::Error::new(HEAP_DUMP_END_KIND, "heap_dump_end")),
            _ => r.skip(length),
        })();
        match result {
            Ok(()) => {}
            Err(e) if e.kind() == HEAP_DUMP_END_KIND => break,
            Err(e)
                if e.kind() == ErrorKind::UnexpectedEof || e.kind() == ErrorKind::InvalidData =>
            {
                break;
            }
            Err(e) => return Err(e),
        }
    }
    Ok(())
}

/// A single materialized heap object record, passed to the [`scan_all_records`]
/// callback. Borrows the reused scratch buffer, so it is valid only for the
/// duration of one callback invocation.
pub(crate) enum Record<'a> {
    /// INSTANCE_DUMP: `(obj_addr, class_id, &blob)`.
    Instance(u64, u64, &'a [u8]),
    /// PRIM_ARRAY_DUMP: `(addr, elem_type_code, count, &raw_bytes)`.
    PrimArray(u64, u8, u64, &'a [u8]),
    /// OBJ_ARRAY_DUMP: `(addr, array_class_id, count, &elem_ref_bytes)`.
    ObjArray(u64, u64, u64, &'a [u8]),
}

/// Single full-file sequential scan over all heap object records. For every
/// INSTANCE_DUMP / PRIM_ARRAY_DUMP / OBJ_ARRAY_DUMP sub-record it invokes `f`
/// once with the matching [`Record`] variant. Fuses what were three separate
/// full-file scans (instances, primitive arrays, object arrays) into ONE read.
///
/// A single callback (rather than three) is deliberate: the three fused scan
/// bodies mutate overlapping accumulator state, and three separate `FnMut`
/// arguments cannot each hold a `&mut` to the same variable at once.
///
/// The skip skeleton + byte accounting are identical to the three single-record
/// scanners; only ONE record's bytes are materialized at a time (three separate
/// reused scratch buffers, each holding one record), so peak RSS is unchanged
/// versus running the three scans back-to-back — but the file is read ONCE
/// instead of three times.
///
/// Callers that have a cross-record ordering dependency (e.g. an obj-array whose
/// owning collection instance may appear later in the file) must NOT resolve it
/// inline here; collect the raw per-record data and resolve it in a cheap
/// in-memory post-pass. HPROF gives no record-ordering guarantee.
pub(crate) fn scan_all_records<O, F>(open: O, id_size: u8, mut f: F) -> io::Result<()>
where
    O: Fn() -> io::Result<HprofReader>,
    F: FnMut(Record<'_>),
{
    let ids = id_size as u64;
    let mut r = open()?;
    // One reused scratch per record kind; only one is live at any instant.
    let mut inst_scratch: Vec<u8> = Vec::with_capacity(256);
    let mut prim_scratch: Vec<u8> = Vec::with_capacity(256);
    let mut obj_scratch: Vec<u8> = Vec::with_capacity(256);
    loop {
        let (tag, length) = match r.next_record()? {
            None => break,
            Some(h) => h,
        };
        let result: io::Result<()> = (|| match tag {
            tags::HEAP_DUMP | tags::HEAP_DUMP_SEGMENT => {
                let mut remaining = length;
                while remaining > 0 {
                    let sub_tag = r.u1()?;
                    sub_remaining(&mut remaining, 1)?;
                    match sub_tag {
                        heap::ROOT_SYSTEM_CLASS
                        | heap::ROOT_UNKNOWN
                        | heap::ROOT_MONITOR_USED
                        | heap::ROOT_STICKY_CLASS
                        | heap::ROOT_INTERNED_STRING
                        | heap::ROOT_DEBUGGER
                        | heap::ROOT_VM_INTERNAL => {
                            r.skip(ids)?;
                            sub_remaining(&mut remaining, ids)?;
                        }
                        heap::ROOT_JNI_GLOBAL => {
                            r.skip(2 * ids)?;
                            sub_remaining(&mut remaining, 2 * ids)?;
                        }
                        heap::ROOT_JNI_LOCAL
                        | heap::ROOT_JAVA_FRAME
                        | heap::ROOT_JNI_MONITOR
                        | heap::ROOT_THREAD_OBJ => {
                            r.skip(ids + 8)?;
                            sub_remaining(&mut remaining, ids + 8)?;
                        }
                        heap::ROOT_NATIVE_STACK | heap::ROOT_THREAD_BLOCK => {
                            r.skip(ids + 4)?;
                            sub_remaining(&mut remaining, ids + 4)?;
                        }
                        heap::HEAP_DUMP_INFO => {
                            r.skip(4 + ids)?;
                            sub_remaining(&mut remaining, 4 + ids)?;
                        }
                        heap::CLASS_DUMP => {
                            let consumed = skip_class_dump(&mut r, id_size)?;
                            sub_remaining(&mut remaining, consumed)?;
                        }
                        heap::INSTANCE_DUMP => {
                            let addr = r.id()?;
                            r.skip(4)?;
                            let class_id = r.id()?;
                            let data_len = r.u4()? as u64;
                            sub_remaining(&mut remaining, ids + 4 + ids + 4 + data_len)?;
                            r.read_bytes_reuse(&mut inst_scratch, data_len as usize)?;
                            f(Record::Instance(addr, class_id, &inst_scratch));
                        }
                        heap::OBJ_ARRAY_DUMP => {
                            let addr = r.id()?;
                            r.skip(4)?; // stack serial
                            let count = r.u4()? as u64;
                            let array_class_id = r.id()?; // array class id
                            let byte_len = count.saturating_mul(ids);
                            sub_remaining(&mut remaining, ids + 4 + 4 + ids + byte_len)?;
                            r.read_bytes_reuse(&mut obj_scratch, byte_len as usize)?;
                            f(Record::ObjArray(addr, array_class_id, count, &obj_scratch));
                        }
                        heap::PRIM_ARRAY_NODATA_DUMP => {
                            // Android ART: same header as PRIM_ARRAY_DUMP but no element data.
                            r.skip(ids + 4 + 4 + 1)?;
                            sub_remaining(&mut remaining, ids + 4 + 4 + 1)?;
                        }

                        heap::PRIM_ARRAY_DUMP => {
                            let addr = r.id()?;
                            r.skip(4)?;
                            let count = r.u4()? as u64;
                            let elem_type = r.u1()?;
                            let esz = HprofType::from_code(elem_type)
                                .map(|t| t.byte_size() as u64)
                                .unwrap_or(1);
                            let byte_len = count.saturating_mul(esz);
                            sub_remaining(&mut remaining, ids + 4 + 4 + 1 + byte_len)?;
                            r.read_bytes_reuse(&mut prim_scratch, byte_len as usize)?;
                            f(Record::PrimArray(addr, elem_type, count, &prim_scratch));
                        }
                        other => {
                            return Err(io::Error::new(
                                ErrorKind::InvalidData,
                                format!("unknown heap sub-tag 0x{other:02x} in fused record scan"),
                            ));
                        }
                    }
                }
                Ok(())
            }
            tags::HEAP_DUMP_END => Err(io::Error::new(HEAP_DUMP_END_KIND, "heap_dump_end")),
            _ => r.skip(length),
        })();
        match result {
            Ok(()) => {}
            Err(e) if e.kind() == HEAP_DUMP_END_KIND => break,
            Err(e)
                if e.kind() == ErrorKind::UnexpectedEof || e.kind() == ErrorKind::InvalidData =>
            {
                break;
            }
            Err(e) => return Err(e),
        }
    }
    Ok(())
}

/// Full-file sequential scan invoking `f(class_obj_id, &statics)` for every
/// CLASS_DUMP sub-record, where `statics` is the captured list of static fields
/// as `(name_id, type_code, value)`. Object-typed values are id_size-wide refs;
/// primitive values are zero-extended into the u64. Only the (bounded) static
/// header of each class is materialized — instance-field descriptors are
/// skipped — so RSS stays O(#static-fields-of-one-class) inside the closure.
pub(crate) fn scan_class_dumps<O, F>(open: O, id_size: u8, mut f: F) -> io::Result<()>
where
    O: Fn() -> io::Result<HprofReader>,
    F: FnMut(u64, &[(u64, u8, u64)]),
{
    let ids = id_size as u64;
    let mut r = open()?;
    let mut statics: Vec<(u64, u8, u64)> = Vec::new();
    let mut vbuf: Vec<u8> = Vec::with_capacity(8);
    loop {
        let (tag, length) = match r.next_record()? {
            None => break,
            Some(h) => h,
        };
        let result: io::Result<()> = (|| match tag {
            tags::HEAP_DUMP | tags::HEAP_DUMP_SEGMENT => {
                let mut remaining = length;
                while remaining > 0 {
                    let sub_tag = r.u1()?;
                    sub_remaining(&mut remaining, 1)?;
                    match sub_tag {
                        heap::ROOT_SYSTEM_CLASS
                        | heap::ROOT_UNKNOWN
                        | heap::ROOT_MONITOR_USED
                        | heap::ROOT_STICKY_CLASS
                        | heap::ROOT_INTERNED_STRING
                        | heap::ROOT_DEBUGGER
                        | heap::ROOT_VM_INTERNAL => {
                            r.skip(ids)?;
                            sub_remaining(&mut remaining, ids)?;
                        }
                        heap::ROOT_JNI_GLOBAL => {
                            r.skip(2 * ids)?;
                            sub_remaining(&mut remaining, 2 * ids)?;
                        }
                        heap::ROOT_JNI_LOCAL
                        | heap::ROOT_JAVA_FRAME
                        | heap::ROOT_JNI_MONITOR
                        | heap::ROOT_THREAD_OBJ => {
                            r.skip(ids + 8)?;
                            sub_remaining(&mut remaining, ids + 8)?;
                        }
                        heap::ROOT_NATIVE_STACK | heap::ROOT_THREAD_BLOCK => {
                            r.skip(ids + 4)?;
                            sub_remaining(&mut remaining, ids + 4)?;
                        }
                        heap::HEAP_DUMP_INFO => {
                            r.skip(4 + ids)?;
                            sub_remaining(&mut remaining, 4 + ids)?;
                        }
                        heap::CLASS_DUMP => {
                            let mut consumed = 0u64;
                            let class_obj_id = r.id()?;
                            r.skip(4)?; // stack serial
                            r.skip(ids * 6)?; // super, loader, signer, protdomain, r1, r2
                            r.skip(4)?; // instance size
                            consumed += ids + 4 + ids * 6 + 4;
                            // Constant pool: u2 count, entries (u2 idx, u1 type, value).
                            let cp_count = r.u2()?;
                            consumed += 2;
                            for _ in 0..cp_count {
                                r.skip(2)?;
                                let type_code = r.u1()?;
                                let vs = value_size(type_code, id_size);
                                r.skip(vs)?;
                                consumed += 2 + 1 + vs;
                            }
                            // Static fields: u2 count, entries (name_id, u1 type, value).
                            statics.clear();
                            let static_count = r.u2()?;
                            consumed += 2;
                            for _ in 0..static_count {
                                let name_id = r.id()?;
                                let type_code = r.u1()?;
                                let vs = value_size(type_code, id_size);
                                let value = if vs == 0 {
                                    0
                                } else {
                                    r.read_bytes_reuse(&mut vbuf, vs as usize)?;
                                    // Big-endian value; only OBJECT (id-wide)
                                    // values are consumed downstream, but decode
                                    // any width uniformly into the low bytes.
                                    let mut acc = 0u64;
                                    for &b in vbuf.iter() {
                                        acc = (acc << 8) | b as u64;
                                    }
                                    acc
                                };
                                consumed += ids + 1 + vs;
                                statics.push((name_id, type_code, value));
                            }
                            // Instance fields: u2 count, entries (name_id, u1 type).
                            let inst_count = r.u2()?;
                            consumed += 2;
                            for _ in 0..inst_count {
                                r.skip(ids)?;
                                r.skip(1)?;
                                consumed += ids + 1;
                            }
                            f(class_obj_id, &statics);
                            sub_remaining(&mut remaining, consumed)?;
                        }
                        heap::INSTANCE_DUMP => {
                            r.skip(ids + 4)?;
                            let _class_id = r.id()?;
                            let data_len = r.u4()? as u64;
                            r.skip(data_len)?;
                            sub_remaining(&mut remaining, ids + 4 + ids + 4 + data_len)?;
                        }
                        heap::OBJ_ARRAY_DUMP => {
                            r.skip(ids + 4)?;
                            let count = r.u4()? as u64;
                            r.skip(ids)?;
                            let byte_len = count.saturating_mul(ids);
                            r.skip(byte_len)?;
                            sub_remaining(&mut remaining, ids + 4 + 4 + ids + byte_len)?;
                        }
                        heap::PRIM_ARRAY_NODATA_DUMP => {
                            // Android ART: same header as PRIM_ARRAY_DUMP but no element data.
                            r.skip(ids + 4 + 4 + 1)?;
                            sub_remaining(&mut remaining, ids + 4 + 4 + 1)?;
                        }

                        heap::PRIM_ARRAY_DUMP => {
                            r.skip(ids + 4)?;
                            let count = r.u4()? as u64;
                            let elem_type = r.u1()?;
                            let esz = HprofType::from_code(elem_type)
                                .map(|t| t.byte_size() as u64)
                                .unwrap_or(1);
                            r.skip(count.saturating_mul(esz))?;
                            sub_remaining(
                                &mut remaining,
                                ids + 4 + 4 + 1 + count.saturating_mul(esz),
                            )?;
                        }
                        other => {
                            return Err(io::Error::new(
                                ErrorKind::InvalidData,
                                format!("unknown heap sub-tag 0x{other:02x} in class-dump scan"),
                            ));
                        }
                    }
                }
                Ok(())
            }
            tags::HEAP_DUMP_END => Err(io::Error::new(HEAP_DUMP_END_KIND, "heap_dump_end")),
            _ => r.skip(length),
        })();
        match result {
            Ok(()) => {}
            Err(e) if e.kind() == HEAP_DUMP_END_KIND => break,
            Err(e)
                if e.kind() == ErrorKind::UnexpectedEof || e.kind() == ErrorKind::InvalidData =>
            {
                break;
            }
            Err(e) => return Err(e),
        }
    }
    Ok(())
}

/// Skip a CLASS_DUMP sub-record, returning the byte count consumed AFTER the
/// 1-byte sub-tag (which the caller has already read). Mirrors the CLASS_DUMP
/// layout in pass1's `read_class_dump`: fixed header, constant pool, static
/// fields, instance-field descriptors.
pub(crate) fn skip_class_dump(r: &mut HprofReader, id_size: u8) -> io::Result<u64> {
    let ids = id_size as u64;
    let mut consumed = 0u64;
    // class_obj_id, stack_serial(4), super_id, loader_id, signer, protdomain,
    // reserved1, reserved2, instance_size(4)
    r.skip(ids)?; // class_obj_id
    r.skip(4)?; // stack serial
    r.skip(ids * 6)?; // super, loader, signer, protection domain, reserved1, reserved2
    r.skip(4)?; // instance_size
    consumed += ids + 4 + ids * 6 + 4;
    // Constant pool: u2 count, then entries of (u2 index, u1 type, value)
    let cp_count = r.u2()?;
    consumed += 2;
    for _ in 0..cp_count {
        r.skip(2)?; // constant pool index
        let type_code = r.u1()?;
        let vs = value_size(type_code, id_size);
        r.skip(vs)?;
        consumed += 2 + 1 + vs;
    }
    // Static fields: u2 count, then (name_id, u1 type, value)
    let static_count = r.u2()?;
    consumed += 2;
    for _ in 0..static_count {
        r.skip(ids)?; // name_id
        let type_code = r.u1()?;
        let vs = value_size(type_code, id_size);
        r.skip(vs)?;
        consumed += ids + 1 + vs;
    }
    // Instance fields: u2 count, then (name_id, u1 type)
    let inst_count = r.u2()?;
    consumed += 2;
    for _ in 0..inst_count {
        r.skip(ids)?; // name_id
        r.skip(1)?; // type
        consumed += ids + 1;
    }
    Ok(consumed)
}

/// Read a big-endian object reference of `ref_size` (4 or 8) bytes from the
/// front of `data`; returns 0 if the slice is too short.
pub(crate) fn read_ref(data: &[u8], ref_size: usize) -> u64 {
    if ref_size == 4 {
        if data.len() >= 4 {
            u32::from_be_bytes([data[0], data[1], data[2], data[3]]) as u64
        } else {
            0
        }
    } else if data.len() >= 8 {
        u64::from_be_bytes([
            data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
        ])
    } else {
        0
    }
}

/// Read a big-endian HPROF id of `id_size` (4 or 8) bytes from the front of
/// `chunk`; returns 0 if the slice is too short.
pub(crate) fn read_id(chunk: &[u8], id_size: u8) -> u64 {
    if id_size == 4 {
        if chunk.len() >= 4 {
            u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]) as u64
        } else {
            0
        }
    } else if chunk.len() >= 8 {
        u64::from_be_bytes([
            chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
        ])
    } else {
        0
    }
}

/// Read one id-sized reference directly from the streaming reader.
pub(crate) fn read_id_from_reader(r: &mut HprofReader, _id_size: u8) -> io::Result<u64> {
    r.id()
}

/// On-disk byte width of a static/constant-pool value of the given HPROF type
/// code (Object = `id_size`; unknown code = 0).
pub(crate) fn value_size(type_code: u8, id_size: u8) -> u64 {
    match HprofType::from_code(type_code) {
        Some(HprofType::Object) => id_size as u64,
        Some(t) => t.byte_size() as u64,
        None => 0,
    }
}

/// Single-pass collection of instance blobs and primitive-array blobs for
/// multiple disjoint wanted sets, avoiding repeated full-file scans.
///
/// Returns:
/// - `inst_blobs`: addr → (class_id, blob bytes), for every addr in
///   `wanted_inst` that appears in the dump as an INSTANCE_DUMP.
/// - `prim_blobs`: addr → blob bytes, for every addr in `wanted_prim` that
///   appears as a PRIM_ARRAY_DUMP.
/// - `obj_blobs`: addr → element-ref bytes, for every addr in `wanted_obj`
///   that appears as an OBJ_ARRAY_DUMP.
#[allow(clippy::type_complexity)]
pub(crate) fn collect_blobs<O>(
    open: O,
    id_size: u8,
    wanted_inst: &std::collections::HashSet<u64>,
    wanted_prim: &std::collections::HashSet<u64>,
    wanted_obj: &std::collections::HashSet<u64>,
) -> io::Result<(
    std::collections::HashMap<u64, (u64, Vec<u8>)>,
    std::collections::HashMap<u64, Vec<u8>>,
    std::collections::HashMap<u64, Vec<u8>>,
)>
where
    O: Fn() -> io::Result<HprofReader>,
{
    use crate::types::{HprofType, heap, tags};
    let ids = id_size as u64;
    let mut inst_blobs: std::collections::HashMap<u64, (u64, Vec<u8>)> =
        std::collections::HashMap::new();
    let mut prim_blobs: std::collections::HashMap<u64, Vec<u8>> = std::collections::HashMap::new();
    let mut obj_blobs: std::collections::HashMap<u64, Vec<u8>> = std::collections::HashMap::new();

    if wanted_inst.is_empty() && wanted_prim.is_empty() && wanted_obj.is_empty() {
        return Ok((inst_blobs, prim_blobs, obj_blobs));
    }

    let mut r = open()?;
    let mut scratch: Vec<u8> = Vec::with_capacity(256);
    loop {
        let (tag, length) = match r.next_record()? {
            None => break,
            Some(h) => h,
        };
        let result: io::Result<()> = (|| match tag {
            tags::HEAP_DUMP | tags::HEAP_DUMP_SEGMENT => {
                let mut remaining = length;
                while remaining > 0 {
                    let sub_tag = r.u1()?;
                    sub_remaining(&mut remaining, 1)?;
                    match sub_tag {
                        heap::ROOT_SYSTEM_CLASS
                        | heap::ROOT_UNKNOWN
                        | heap::ROOT_MONITOR_USED
                        | heap::ROOT_STICKY_CLASS
                        | heap::ROOT_INTERNED_STRING
                        | heap::ROOT_DEBUGGER
                        | heap::ROOT_VM_INTERNAL => {
                            r.skip(ids)?;
                            sub_remaining(&mut remaining, ids)?;
                        }
                        heap::ROOT_JNI_GLOBAL => {
                            r.skip(2 * ids)?;
                            sub_remaining(&mut remaining, 2 * ids)?;
                        }
                        heap::ROOT_JNI_LOCAL
                        | heap::ROOT_JAVA_FRAME
                        | heap::ROOT_JNI_MONITOR
                        | heap::ROOT_THREAD_OBJ => {
                            r.skip(ids + 8)?;
                            sub_remaining(&mut remaining, ids + 8)?;
                        }
                        heap::ROOT_NATIVE_STACK | heap::ROOT_THREAD_BLOCK => {
                            r.skip(ids + 4)?;
                            sub_remaining(&mut remaining, ids + 4)?;
                        }
                        heap::HEAP_DUMP_INFO => {
                            r.skip(4 + ids)?;
                            sub_remaining(&mut remaining, 4 + ids)?;
                        }
                        heap::CLASS_DUMP => {
                            let consumed = skip_class_dump(&mut r, id_size)?;
                            sub_remaining(&mut remaining, consumed)?;
                        }
                        heap::INSTANCE_DUMP => {
                            let addr = r.id()?;
                            r.skip(4)?;
                            let class_id = r.id()?;
                            let data_len = r.u4()? as u64;
                            sub_remaining(&mut remaining, ids + 4 + ids + 4 + data_len)?;
                            if wanted_inst.contains(&addr) {
                                r.read_bytes_reuse(&mut scratch, data_len as usize)?;
                                inst_blobs.insert(addr, (class_id, scratch.clone()));
                            } else {
                                r.skip(data_len)?;
                            }
                        }
                        heap::OBJ_ARRAY_DUMP => {
                            let addr = r.id()?;
                            r.skip(4)?;
                            let count = r.u4()? as u64;
                            r.skip(ids)?;
                            let byte_len = count.saturating_mul(ids);
                            sub_remaining(&mut remaining, ids + 4 + 4 + ids + byte_len)?;
                            if wanted_obj.contains(&addr) {
                                r.read_bytes_reuse(&mut scratch, byte_len as usize)?;
                                obj_blobs.insert(addr, scratch.clone());
                            } else {
                                r.skip(byte_len)?;
                            }
                        }
                        heap::PRIM_ARRAY_NODATA_DUMP => {
                            // Android ART: same header as PRIM_ARRAY_DUMP but no element data.
                            r.skip(ids + 4 + 4 + 1)?;
                            sub_remaining(&mut remaining, ids + 4 + 4 + 1)?;
                        }

                        heap::PRIM_ARRAY_DUMP => {
                            let addr = r.id()?;
                            r.skip(4)?;
                            let count = r.u4()? as u64;
                            let elem_type = r.u1()?;
                            let esz = HprofType::from_code(elem_type)
                                .map(|t| t.byte_size() as u64)
                                .unwrap_or(1);
                            let byte_len = count.saturating_mul(esz);
                            sub_remaining(&mut remaining, ids + 4 + 4 + 1 + byte_len)?;
                            if wanted_prim.contains(&addr) {
                                r.read_bytes_reuse(&mut scratch, byte_len as usize)?;
                                prim_blobs.insert(addr, scratch.clone());
                            } else {
                                r.skip(byte_len)?;
                            }
                        }
                        other => {
                            return Err(io::Error::new(
                                ErrorKind::InvalidData,
                                format!("unknown heap sub-tag 0x{other:02x} in collect_blobs"),
                            ));
                        }
                    }
                }
                Ok(())
            }
            tags::HEAP_DUMP_END => Err(io::Error::new(HEAP_DUMP_END_KIND, "heap_dump_end")),
            _ => r.skip(length),
        })();
        match result {
            Ok(()) => {}
            Err(e) if e.kind() == HEAP_DUMP_END_KIND => break,
            Err(e)
                if e.kind() == ErrorKind::UnexpectedEof || e.kind() == ErrorKind::InvalidData =>
            {
                break;
            }
            Err(e) => return Err(e),
        }
    }
    Ok((inst_blobs, prim_blobs, obj_blobs))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sub_remaining_errors_on_underflow_instead_of_wrapping() {
        // Normal accounting decrements in place.
        let mut rem = 100u64;
        sub_remaining(&mut rem, 40).unwrap();
        assert_eq!(rem, 60);
        sub_remaining(&mut rem, 60).unwrap();
        assert_eq!(rem, 0);

        // A sub-record claiming more bytes than the segment has left must error
        // (InvalidData), NOT wrap to ~u64::MAX and spin the scan loop into OOB
        // reads. This is the malformed/truncated HEAP_DUMP_SEGMENT case.
        let mut rem = 3u64;
        let err = sub_remaining(&mut rem, 4).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidData);
        // On error the counter is left unchanged (no partial mutation).
        assert_eq!(rem, 3);
    }
}