jscd 0.1.0

Reverse bytenode-compiled .jsc (V8 code cache) back to JavaScript
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
//! 反汇编渲染:对齐 V8 `--print-bytecode` / View8 反汇编器文本格式。
//!
//! 输出每函数形如(与 V8 printer 同形,便于与 `node --print-bytecode` 对拍):
//! ```text
//! [generated bytecode for function: add (jscd <SharedFunctionInfo add>)]
//! Bytecode length: 6
//! Parameter count 3
//! Register count 0
//! Frame size 0
//! OSR nesting level: 0
//! Bytecode Age: 0
//!          0 @    0 : 0b 04              Ldar a1
//! Constant pool (size = 1)
//! Handler Table (size = 0)
//! Source Position Table (size = 7)
//! ```

use crate::bytecode::{Decoder, FamilyLayout, Instr, Operand};
use crate::serializer::{CodeCache, Elem, ObjId, Ref, SlotValue};
use crate::tables::VersionTable;
use std::fmt::Write as _;

/// 9.x 家族兜底槽位(表缺 layout 时使用)。
mod fallback_slots {
    /// SFI:function_data / name_or_scope_info / script
    pub const SFI_FUNCTION_DATA: usize = 1;
    pub const SFI_NAME: usize = 2;
    /// BCA:constant_pool / handler_table / source_position_table
    pub const BCA_CONSTANT_POOL: usize = 2;
    pub const BCA_HANDLER_TABLE: usize = 3;
    pub const BCA_SOURCE_POSITION_TABLE: usize = 4;
}

pub struct Disassembler<'a> {
    cache: &'a CodeCache<'a>,
    table: &'a VersionTable,
    layout: FamilyLayout,
    /// 源码占位字符串长度(attached ref 0 展示用,来自头部 source_hash)
    source_len: u32,
    /// 只读堆名表:13.x 起函数名/属性名常以 `ro{chunk}/{offset}` 引用出现,
    /// 没有它只能回落成空字符串(node24 的 `count` 因此成了匿名函数,
    /// 调用点 `count(...)` 找的是全局名 → 生成器 fixture 全空)
    ro_map: Option<std::rc::Rc<crate::decompile::RoMap>>,
}

impl<'a> Disassembler<'a> {
    /// SFI 槽位:function_data(含 13.6 的 trusted/untrusted 拆分)。
    pub fn sfi_function_data_slots(&self) -> Vec<usize> {
        let ts = self.layout.tagged_size;
        if let Some(sfi) = &self.table.shared_function_info {
            let v: Vec<usize> = ["function_data", "trusted_function_data", "untrusted_function_data"]
                .iter()
                .filter_map(|n| sfi.slot(ts, n))
                .collect();
            if !v.is_empty() {
                return v;
            }
        }
        vec![fallback_slots::SFI_FUNCTION_DATA]
    }

    pub fn sfi_name_slot(&self) -> usize {
        let ts = self.layout.tagged_size;
        self.table
            .shared_function_info
            .as_ref()
            .and_then(|s| s.slot(ts, "name_or_scope_info"))
            .unwrap_or(fallback_slots::SFI_NAME)
    }

    fn bca_slot(&self, names: &[&str], fallback: usize) -> usize {
        let ts = self.layout.tagged_size;
        self.table
            .bytecode_array
            .as_ref()
            .and_then(|b| b.fields.get(*names.first().unwrap()).copied().map(|o| o / ts))
            .or_else(|| {
                self.table
                    .bytecode_array
                    .as_ref()
                    .and_then(|b| names.iter().find_map(|n| b.fields.get(*n).copied().map(|o| o / ts)))
            })
            .unwrap_or(fallback)
    }

    pub fn bca_constant_pool_slot(&self) -> usize {
        self.bca_slot(&["constant_pool"], fallback_slots::BCA_CONSTANT_POOL)
    }
    pub fn bca_handler_table_slot(&self) -> usize {
        self.bca_slot(&["handler_table"], fallback_slots::BCA_HANDLER_TABLE)
    }
    pub fn bca_source_position_slot(&self) -> usize {
        self.bca_slot(&["source_position_table"], fallback_slots::BCA_SOURCE_POSITION_TABLE)
    }

    pub fn new(cache: &'a CodeCache<'a>, table: &'a VersionTable, layout: FamilyLayout) -> Self {
        Disassembler {
            cache,
            table,
            layout,
            source_len: 0,
            ro_map: None,
        }
    }

    /// 附上只读堆名表(`--ro-map`)。
    pub fn with_ro_map(mut self, m: Option<std::rc::Rc<crate::decompile::RoMap>>) -> Self {
        self.ro_map = m;
        self
    }

    /// 渲染全部函数(按对象序 = 序列化序)。
    pub fn render_all(&self, filter: Option<&str>) -> Result<String, String> {
        let mut out = String::new();
        for id in 0..self.cache.objects.len() {
            if !self.cache.obj(id).ty.is(self.table, "SharedFunctionInfo") {
                continue;
            }
            let name = self.sfi_name(id);
            if let Some(f) = filter {
                if !name.contains(f) {
                    continue;
                }
            }
            self.render_sfi(id, &name, &mut out)?;
        }
        Ok(out)
    }

    /// 函数名。取值链对齐 V8 `SharedFunctionInfo::DebugName()`:
    /// name_or_scope_info 为 String 直接用;为 ScopeInfo 时读 FunctionName
    /// (function_variable_info.name),空则回落 inferred_function_name。
    pub fn sfi_name(&self, id: ObjId) -> String {
        if std::env::var("JSCD_DBG_SFI").is_ok() {
            let n = self.cache.array_len(id).max(16);
            let mut out = Vec::new();
            for i in 0..n.min(16) {
                out.push(match self.cache.slot_at(id, i) {
                    Some(SlotValue::Ref(r)) => format!("{i}:{}", self.describe_ref(r)),
                    Some(other) => format!("{i}:{other:?}"),
                    None => format!("{i}:-"),
                });
            }
            eprintln!(
                "[sfi] id={id} name_slot={} slots={out:?}",
                self.sfi_name_slot()
            );
            if let Some(SlotValue::Ref(Ref::Object(sid))) = self.cache.slot_at(id, self.sfi_name_slot())
            {
                let sid = *sid;
                if self.cache.obj(sid).ty.is(self.table, "ScopeInfo") {
                    let ts = self.layout.tagged_size;
                    let raw: Vec<String> = (0..6)
                        .map(|k| {
                            self.cache
                                .raw_at(sid, k * ts, 8)
                                .map(|d| {
                                    let v = u64::from_le_bytes(d.try_into().unwrap());
                                    format!("{v:#x}")
                                })
                                .unwrap_or_else(|| "-".into())
                        })
                        .collect();
                    eprintln!(
                        "[sfi]   scope id={sid} byte_size={} array_len={} ts={ts} words={raw:?}",
                        self.cache.obj(sid).byte_size,
                        self.cache.array_len(sid)
                    );
                }
            }
        }
        let Some(SlotValue::Ref(r)) = self.cache.slot_at(id, self.sfi_name_slot()) else {
            return String::new();
        };
        match r {
            Ref::Object(sid) if self.cache.obj(*sid).ty.is(self.table, "ScopeInfo") => {
                let name = self.scope_function_name(*sid);
                if name.is_empty() {
                    self.scope_inferred_name(*sid)
                } else {
                    name
                }
            }
            other => self.name_from_ref(*other),
        }
    }

    /// Ref → 名字字符串(String 对象 / 名字根)。
    fn name_from_ref(&self, r: Ref) -> String {
        match r {
            Ref::Object(sid) => {
                let o = self.cache.obj(sid);
                if o.ty.is_string(self.table) {
                    self.string_value(sid).unwrap_or_default()
                } else {
                    String::new()
                }
            }
            Ref::Root(i) => {
                let n = self.table.root_name(i).unwrap_or_default().to_string();
                n.strip_prefix("String:").map(str::to_string).unwrap_or_default()
            }
            Ref::RoRef(c, off) => self
                .ro_map
                .as_deref()
                .and_then(|m| m.get(c, off))
                .map(str::to_string)
                .unwrap_or_default(),
            _ => String::new(),
        }
    }

    /// ScopeInfo 名字段位置(按版本布局逐段推进,返回 (function_name_slot, inferred_slot))。
    ///
    /// 9.x–12.x:flags(Smi) | parameter_count | context_local_count | names[n] | infos[n] |
    ///           [saved] | [receiver] | [function_variable_info{name,index}] | [inferred] | ...
    /// 13.x:    flags(u32) + padding | parameter_count | context_local_count |
    ///           position_info(2) | [module_count] | names[n] (n<75) | [hashtable] | infos[n] |
    ///           [saved] | [function_variable_info] | [inferred] | ...
    /// ScopeInfo 数值域(Flags/ParameterCount/ContextLocalCount,各占一个 slot)。
    ///
    /// 存储形态随版本变:9.x–12.x 是 Smi(值在高 32 位),13.x 是裸 int32(低 32 位)。
    /// ≤8.4 的 accessor 是 `FOR_EACH_SCOPE_INFO_NUMERIC_FIELD` 宏生成的
    /// (scope-info.cc 里 `Smi::ToInt(get(...))`),codegen 没认出来、表里标了
    /// `flags_smi: false` —— 实测读低 4 字节恒为 0,于是 flags/形参名全丢。
    /// 这里自适应:低 4 字节为 0 而 Smi 半边非 0 → 说明其实是 Smi 存储。
    fn num_field(&self, id: ObjId, slot: usize, flags_smi: bool) -> Option<u32> {
        let raw = self
            .cache
            .raw_at(id, slot * self.layout.tagged_size, 4)
            .map(|d| u32::from_le_bytes(d.try_into().unwrap()));
        let smi = self.smi_slot(id, slot).map(|v| v as u32);
        match (flags_smi, raw, smi) {
            (true, _, Some(s)) => Some(s),
            (false, Some(0), Some(s)) if s != 0 => Some(s),
            (false, Some(r), _) => Some(r),
            (_, _, s) => s.or(raw),
        }
    }

    /// ScopeInfo 数值域的**起点**(Flags 在哪个槽)随版本变:
    ///   ≤8.4:头两格是 map+length → Flags 槽 2;
    ///   9.x+:Flags 槽 1 —— 但 **9.0(node16.0–16.3)例外**:实测它的 ScopeInfo 比 9.1+
    ///   多一格(16.3 的槽 1 是个无关的小整数、槽 2 才是 flags=0x3044;16.5 槽 1 就是 flags),
    ///   于是按槽 1 读会把函数名全丢(产物里函数叫 `_anon_4`、形参个数也多一个)。
    /// 与其按版本硬编码,不如按**结果**挑:哪个起点能让"名字槽真的指向字符串"就用哪个。
    fn scope_name_slots(&self, id: ObjId) -> (Option<usize>, Option<usize>) {
        let legacy = self.table.v8.starts_with('8')
            || self.table.v8.starts_with('7')
            || self.table.v8.starts_with('6');
        let primary = if legacy { 2 } else { 1 };
        let mut best = (None, None);
        let mut best_score = -1i32;
        for base in [primary, if primary == 1 { 2 } else { 1 }] {
            let (n, inf) = self.scope_name_slots_with(id, base);
            let mut score = 0i32;
            if n.map(|s| self.slot_looks_like_name(id, s)).unwrap_or(false) {
                score += 2;
            }
            if inf.map(|s| self.slot_looks_like_name(id, s)).unwrap_or(false) {
                score += 1;
            }
            if score > best_score {
                best_score = score;
                best = (n, inf);
            }
            if score >= 2 {
                break;   // 已经拿到真名字,不再试另一个起点
            }
        }
        best
    }

    /// 该槽是不是"名字":指向字符串对象,或指向 `String:` 名字根。
    fn slot_looks_like_name(&self, id: ObjId, slot: usize) -> bool {
        match self.cache.slot_at(id, slot) {
            Some(SlotValue::Ref(Ref::Object(o))) => self.cache.obj(*o).ty.is_string(self.table),
            Some(SlotValue::Ref(Ref::Root(r))) => self
                .table
                .root_name(*r)
                .map(|n| n.starts_with("String:"))
                .unwrap_or(false),
            _ => false,
        }
    }

    fn scope_name_slots_with(&self, id: ObjId, base: usize) -> (Option<usize>, Option<usize>) {
        let ts = self.layout.tagged_size;
        let cfg = self.table.scope_info.clone().unwrap_or(crate::tables::ScopeInfoLayout {
            flags_smi: true,
            position_info_early: false,
            max_inlined_names: 75,
            saved_class_bit: 10,
            has_outer_bit: None,
            function_variable_bits: [12, 13],
            receiver_bits: [7, 8],
            has_inferred_bit: 14,
            context_local_count_slot: None,
            variable_part: None,
            parameter_names_first: false,
        });
        // ScopeInfo 的数值域各占一个 slot:9.x–12.x 是 Smi(值在高 32 位),
        // ≤8.4 与 13.x 是**裸 int32**(`FOR_EACH_SCOPE_INFO_NUMERIC_FIELD` 的
        // `inline int name() const`)。原来一律按 Smi 读 —— 老族于是全都读不出来,
        // `scope_name_slots` 直接返回 None,函数名/形参名全丢(node14 产物叫 `_anon_4`)。
        // 数值域起点随版本变:
        //   ≤8.4:ScopeInfo 是 FixedArray,头两格是 map+length → Flags 在**槽 2**、
        //         ParameterCount 槽 3、ContextLocalCount 槽 4,变量区从**槽 5** 起
        //         (实测 node14:槽 5 正是函数名 `String:target` 的根引用)。
        //   9.x+ :Flags 在槽 1(本代码长期验证过的路径)。
        let legacy = base == 2;
        // 数值域的存储形态随版本变:7.8 及更早是 **Smi**(`set(kFlags, Smi::FromInt(v))`),
        // 8.x 是裸 int32,9.x–12.x 又是 Smi,13.x 裸 int32 —— 有版本表就听表的
        // (flags_smi),没有表(6.x 之前)再退回"老族=裸 int32"的老经验。
        let flags_smi = if self.table.scope_info.is_some() { cfg.flags_smi } else { legacy };
        let flags = self.num_field(id, base, flags_smi).unwrap_or(0) as u64;

        let has_saved = (flags >> cfg.saved_class_bit) & 1 == 1;
        let function_var = ((flags >> cfg.function_variable_bits[0])
            & ((1 << (cfg.function_variable_bits[1] - cfg.function_variable_bits[0] + 1)) - 1))
            as u32;
        let has_inferred = (flags >> cfg.has_inferred_bit) & 1 == 1;
        let receiver_var = ((flags >> cfg.receiver_bits[0])
            & ((1 << (cfg.receiver_bits[1] - cfg.receiver_bits[0] + 1)) - 1)) as u32;
        let has_receiver = matches!(receiver_var, 1 | 2);

        if std::env::var("JSCD_DBG_SFI").is_ok() {
            eprintln!(
                "[sfi]   id={id} flags={flags:#x} function_var={function_var} has_inferred={has_inferred} has_saved={has_saved} has_receiver={has_receiver} len={}",
                self.cache.array_len(id)
            );
        }
        if !cfg.position_info_early {
            // 槽位 = (变量区起点) + 2n + saved + receiver;起点 ≤8.4 为 5、9.x–12.x 为 4
            // ContextLocalCount 的槽位随版本:8.x = base+2(槽 4),6.x 多一个
            // StackLocalCount → 槽 5(表里给)。
            let clc_slot = cfg.context_local_count_slot.unwrap_or(base + 2);
            let Some(n) = self.num_field(id, clc_slot, flags_smi) else {
                return (None, None);
            };
            let vpart = cfg
                .variable_part
                .unwrap_or(if legacy { 5 } else { 4 });
            let mut cursor =
                vpart + 2 * n as usize + has_saved as usize + has_receiver as usize;
            if cfg.parameter_names_first {
                // ≤6.x:变量区 = 形参名(ParameterCount) + 栈局部首槽(1) + 栈局部名(StackLocalCount)
                // + context 名 + context 信息 + …,函数名在这些之后。
                let param = self.num_field(id, clc_slot.wrapping_sub(2), flags_smi).unwrap_or(0);
                let stack = self.num_field(id, clc_slot.wrapping_sub(1), flags_smi).unwrap_or(0);
                cursor += param as usize + 1 + stack as usize;
            }
            // V8 `ScopeInfo::HasFunctionName()`(8.4 到 13.x 都是同一条:
            //   `return VariableAllocationInfo::NONE != FunctionVariableBits::decode(Flags());`)
            // —— 只有 NONE(0) 表示"没有名字槽";UNUSED(3) 只是函数变量没被用到,槽位照样
            // 保留(里面是 `kNoSharedNameSentinel`,一个 Smi → 序列化成 raw 字)。
            // 所以判定交给**槽里的值**:是字符串才算名字(`scope_function_name` 对非字符串的
            // Ref/Raw 一律返回空串),非字符串就走 inferred / 匿名。
            // 早先按"必须 STACK/CONTEXT"过滤,把 node14 的真名一起丢了 —— closure 的
            // `target` 在 flags 里就是 function_var=3,产物成了 `_anon_4` → target-missing。
            let function_name = if function_var != 0 {
                let slot = cursor;
                cursor += 2;
                Some(slot)
            } else {
                None
            };
            let inferred = if has_inferred { Some(cursor) } else { None };
            return (function_name, inferred);
        }

        // 13.x:flags+padding(ts+8) | parameter_count(ts+8) | context_local_count(ts+16)
        let param_off = ts + 8;
        let clc_off = ts + 16;
        let _ = param_off;
        let Some(n) = self
            .cache
            .raw_at(id, clc_off, ts)
            .and_then(|d| self.decode_smi_bytes(d))
        else {
            return (None, None);
        };
        let n = n as usize;
        let mut off = clc_off + ts; // 变长区起点(字节)
        off += 2 * ts; // position_info(2 个 Smi)
        let scope_type = flags & 0xF;
        if scope_type == 3 {
            off += ts; // module_variable_count
        }
        if n < cfg.max_inlined_names {
            off += n * ts; // context_local_names
        } else {
            off += ts; // context_local_names_hashtable
        }
        off += n * ts; // context_local_infos
        if has_saved {
            off += ts;
        }
        let function_name = if function_var != 0 {
            let slot = off / ts;
            off += 2 * ts;
            Some(slot)
        } else {
            None
        };
        let inferred = if has_inferred { Some(off / ts) } else { None };
        (function_name, inferred)
    }

    fn scope_function_name(&self, id: ObjId) -> String {
        if std::env::var("JSCD_DBG_SFI").is_ok() {
            let (a, b) = self.scope_name_slots(id);
            eprintln!(
                "[sfi] scope={id} name_slot={a:?} inferred_slot={b:?} v0={:?} v1={:?}",
                a.and_then(|s| self.cache.slot_at(id, s)),
                b.and_then(|s| self.cache.slot_at(id, s))
            );
        }
        match self.scope_name_slots(id).0 {
            Some(slot) => match self.cache.slot_at(id, slot) {
                Some(SlotValue::Ref(r)) => self.name_from_ref(*r),
                _ => String::new(),
            },
            None => String::new(),
        }
    }

    fn scope_inferred_name(&self, id: ObjId) -> String {
        match self.scope_name_slots(id).1 {
            Some(slot) => match self.cache.slot_at(id, slot) {
                Some(SlotValue::Ref(r)) => self.name_from_ref(*r),
                _ => String::new(),
            },
            None => String::new(),
        }
    }

    /// 解 8/4 字节 Smi(无压缩:值在高 32 位;压缩:低 32 位带 tag)。
    fn decode_smi_bytes(&self, d: &[u8]) -> Option<i64> {
        if d.len() == 8 {
            Some((read_u64(d) >> 32) as u32 as i32 as i64)
        } else if d.len() == 4 {
            let raw = u32::from_le_bytes(d.try_into().ok()?);
            if raw & 1 == 0 {
                None
            } else {
                Some(((raw as i32) >> 1) as i64)
            }
        } else {
            None
        }
    }

    /// 读对象内某个 tagged 槽的 Smi 值(无压缩:高 32 位;压缩:低 32 位带 tag)。
    fn smi_slot(&self, id: ObjId, slot: usize) -> Option<i64> {
        let ts = self.layout.tagged_size;
        let d = self.cache.raw_at(id, slot * ts, ts)?;
        if ts == 8 {
            Some((read_u64(d) >> 32) as u32 as i32 as i64)
        } else {
            let raw = u32::from_le_bytes(d.try_into().ok()?);
            Some(((raw as i32) >> 1) as i64)
        }
    }

    fn render_sfi(&self, id: ObjId, name: &str, out: &mut String) -> Result<(), String> {
        // function_data 槽(9.x–12.x 单槽;13.6 起 trusted/untrusted 拆分,取指向 BCA 的那个)
        let mut bca_id = None;
        for slot in self.sfi_function_data_slots() {
            if let Some(SlotValue::Ref(Ref::Object(b))) = self.cache.slot_at(id, slot) {
                if self.cache.obj(*b).ty.is(self.table, "BytecodeArray") {
                    bca_id = Some(*b);
                    break;
                }
            }
        }
        let Some(bca_id) = bca_id else {
            return Ok(()); // 未编译(UncompiledData)——留给 functions 子命令展示
        };
        let ba_layout = self
            .table
            .bytecode_array
            .clone()
            .unwrap_or_else(|| crate::tables::BytecodeArrayLayout::fallback(self.layout.tagged_size));
        let header = ba_layout.header_size;
        let obj = self.cache.obj(bca_id);
        let bytecode_len = self
            .cache
            .raw_at(bca_id, self.layout.tagged_size, self.layout.tagged_size)
            .map(|d| read_u64(d) >> 32)
            .unwrap_or(0) as usize;
        let frame_size = ba_layout
            .off("frame_size")
            .and_then(|o| self.cache.raw_at(bca_id, o, 4))
            .map(|d| u32::from_le_bytes(d.try_into().unwrap()))
            .unwrap_or(0);
        // parameter_size 是字节数;V8 的 parameter_count() = parameter_size / kSystemPointerSize
        let parameter_size = ba_layout
            .off("parameter_size")
            .and_then(|o| self.cache.raw_at(bca_id, o, 4))
            .map(|d| u32::from_le_bytes(d.try_into().unwrap()) as i32)
            .unwrap_or(0);
        // parameter_size 语义随版本变:≤12 存字节数,13.x 起直接是计数
        let parameter_count = if self
            .table
            .parameter_count
            .map(|c| c.direct)
            .unwrap_or(false)
        {
            // 13.x:字段是 uint16,直接就是计数
            parameter_size & 0xFFFF
        } else {
            parameter_size / 8
        };
        // osr 字段名随版本变(osr_loop_nesting_level / osr_urgency_and_install_target);11.3+ 已移除
        let osr = ba_layout
            .off("osr_loop_nesting_level")
            .or_else(|| ba_layout.off("osr_urgency_and_install_target"))
            .and_then(|o| self.cache.raw_at(bca_id, o, 1))
            .map(|d| d[0])
            .unwrap_or(0);
        let age = ba_layout
            .off("bytecode_age")
            .and_then(|o| self.cache.raw_at(bca_id, o, 1))
            .map(|d| d[0])
            .unwrap_or(0);
        let code = self
            .cache
            .raw_at(bca_id, header, bytecode_len)
            .unwrap_or_default();

        let decoder = Decoder::new(self.table, self.layout, parameter_count);
        let instrs = decoder.decode(code).map_err(|e| {
            format!("decode bytecode of '{}' ({} bytes): {e}", name, code.len())
        })?;
        // V8: register_count() = frame_size / kSystemPointerSize
        let register_count = frame_size / 8;

        let _ = writeln!(
            out,
            "[generated bytecode for function: {name} (jscd <SharedFunctionInfo {name}>)]"
        );
        let _ = writeln!(out, "Bytecode length: {bytecode_len}");
        let _ = writeln!(out, "Parameter count {parameter_count}");
        let _ = writeln!(out, "Register count {register_count}");
        let _ = writeln!(out, "Frame size {frame_size}");
        let _ = writeln!(out, "OSR nesting level: {osr}");
        let _ = writeln!(out, "Bytecode Age: {age}");
        for ins in &instrs {
            let hex = ins
                .bytes
                .iter()
                .map(|b| format!("{b:02x} "))
                .collect::<String>();
            let ops = ins
                .operands
                .iter()
                .map(|o| decoder.render_operand(o))
                .collect::<Vec<_>>()
                .join(", ");
            // 跳转目标:V8 打印 " (0xaddr @ target)";我们无地址,用同样形状的 (jscd @ target)
            let jump = self
                .jump_target(bca_id, ins)
                .map(|t| format!(" (jscd @ {t})"))
                .unwrap_or_default();
            // switch 跳转表:{ case: @target, ... }(V8 BytecodeArray::Disassemble 同形)
            let switch = self
                .jump_table(bca_id, ins)
                .map(|entries| {
                    let body = entries
                        .iter()
                        .map(|(c, t)| format!(" {c}: @{t}"))
                        .collect::<Vec<_>>()
                        .join(",");
                    format!(" {{{body} }}")
                })
                .unwrap_or_default();
            let _ = writeln!(
                out,
                "{:>10} @ {:>4} : {:<18} {}{}{}{}",
                "",
                ins.offset,
                hex.trim_end(),
                ins.name,
                if ops.is_empty() { String::new() } else { format!(" {ops}") },
                jump,
                switch
            );
            let _ = &switch;
        }
        self.render_constant_pool(bca_id, out);
        self.render_byte_array(
            "Handler Table",
            self.cache.slot_at(bca_id, self.bca_handler_table_slot()).and_then(|v| v.as_ref()),
            out,
        );
        self.render_byte_array(
            "Source Position Table",
            self.cache
                .slot_at(bca_id, self.bca_source_position_slot())
                .and_then(|v| v.as_ref()),
            out,
        );
        let _ = writeln!(out);
        let _ = obj;
        Ok(())
    }

    fn render_byte_array(&self, label: &str, r: Option<Ref>, out: &mut String) {
        match r {
            Some(Ref::Object(id)) if self.cache.obj(id).ty.is(self.table, "ByteArray") => {
                // 长度在 tag 槽里,但**落在哪半**随版本变(9.x–12.x 在高 32 位,
                // 13.x 搬到低 32 位)→ 两半都取,选像长度的那个(≤ 对象字节数)。
                let obj_bytes = self.cache.obj(id).byte_size;
                let word = self
                    .cache
                    .raw_at(id, self.layout.tagged_size, 8.min(self.layout.tagged_size));
                let len = match word {
                    Some(d) if d.len() == 8 => {
                        let w = read_u64(d);
                        let hi = (w >> 32) as u32 as usize;
                        let lo = (w & 0xffff_ffff) as u32 as usize;
                        if hi <= obj_bytes && (lo > obj_bytes || hi >= lo) {
                            hi
                        } else {
                            lo
                        }
                    }
                    Some(d) if d.len() == 4 => {
                        u32::from_le_bytes(d.try_into().unwrap()) as usize
                    }
                    _ => 0,
                };
                let _ = writeln!(out, "{label} (size = {len})");
            }
            Some(Ref::Root(i)) => {
                let n = self.table.root_name(i).unwrap_or_default().to_string();
                if n.contains("empty_byte_array") || n.contains("EmptyByteArray") {
                    let _ = writeln!(out, "{label} (size = 0)");
                } else {
                    let _ = writeln!(out, "{label} (size = ?)");
                }
            }
            _ => {
                let _ = writeln!(out, "{label} (size = 0)");
            }
        }
    }

    fn render_constant_pool(&self, bca_id: ObjId, out: &mut String) {
        // 常量池:FixedArray(map + length Smi + elements,Smi 与指针交错在 raw/ref 单元里)
        let pool = self
            .cache
            .slot_at(bca_id, self.bca_constant_pool_slot())
            .and_then(|v| v.as_ref())
            .and_then(|r| self.cache.ref_object(r));
        let Some(pool_id) = pool else {
            let _ = writeln!(out, "Constant pool (size = 0)");
            return;
        };
        let entries = self.fixed_array_entries(pool_id);
        let _ = writeln!(out, "Constant pool (size = {})", entries.len());
        for (i, e) in entries.iter().enumerate() {
            let _ = writeln!(out, "{:>12}: {}", i, e);
        }
    }

    /// 跳转目标(对齐 V8 BytecodeArrayIterator::GetJumpTargetOffset)。
    ///
    /// - 立即数形式:目标 = 指令自身偏移 + 相对量(JumpLoop 取负,不是"下一条")
    /// - `*Constant` 形式:相对量取自常量池里的 Smi
    fn jump_target(&self, bca_id: ObjId, ins: &Instr) -> Option<usize> {
        // V8: GetAbsoluteOffset(rel) = current_offset + rel + prefix_size(Wide 前缀占 1 字节)
        let prefix = if ins.scale > 1 { 1 } else { 0 };
        let here = ins.offset + prefix;
        let base = ins.name.trim_end_matches(".Wide").trim_end_matches(".ExtraWide");
        let is_constant = base.ends_with("Constant");
        let rel: i64 = if is_constant {
            let idx = match ins.operands.first()? {
                Operand::Idx(v) => *v as usize,
                _ => return None,
            };
            let pool = self
                .cache
                .slot_at(bca_id, self.bca_constant_pool_slot())
                .and_then(|v| v.as_ref())
                .and_then(|r| self.cache.ref_object(r))?;
            self.cache.array_elem(pool, idx).and_then(|e| e.as_smi())?
        } else {
            match ins.operands.first()? {
                Operand::Idx(v) => *v as i64,
                Operand::Imm(v) => *v,
                _ => return None,
            }
        };
        match base {
            "Jump" | "JumpConstant" | "JumpIfTrue" | "JumpIfTrueConstant" | "JumpIfFalse"
            | "JumpIfFalseConstant" | "JumpIfToBooleanTrue" | "JumpIfToBooleanTrueConstant"
            | "JumpIfToBooleanFalse" | "JumpIfToBooleanFalseConstant" | "JumpIfNull"
            | "JumpIfNullConstant" | "JumpIfNotNull" | "JumpIfNotNullConstant"
            | "JumpIfUndefined" | "JumpIfUndefinedConstant" | "JumpIfUndefinedOrNull"
            | "JumpIfUndefinedOrNullConstant" | "JumpIfNotUndefined"
            | "JumpIfNotUndefinedConstant" | "JumpIfJSReceiver" | "JumpIfJSReceiverConstant"
            | "JumpIfNotHole" | "JumpIfNotHoleConstant" | "JumpIfReferenceError"
            | "JumpIfReferenceErrorConstant" | "JumpIfNotReferenceError"
            | "JumpIfNotReferenceErrorConstant" => {
                Some((here as i64 + rel) as usize)
            }
            "JumpLoop" | "JumpLoopConstant" => {
                (ins.offset as i64 + prefix as i64).checked_sub(rel).map(|v| v as usize)
            }
            _ => None,
        }
    }

    /// switch 跳转表:常量池 [start, start+size) 的 Smi 项,目标 = 指令偏移 + Smi。
    fn jump_table(&self, bca_id: ObjId, ins: &Instr) -> Option<Vec<(i32, usize)>> {
        // SwitchOnSmiNoFeedback: [Idx table_start, UImm size, Imm case_base]
        // SwitchOnGeneratorState: [Reg, Idx table_start, UImm size],case_base = 0
        let (start_idx, size_idx, base_idx, base_fixed) = match ins.name.as_str() {
            "SwitchOnSmiNoFeedback" => (0usize, 1usize, Some(2usize), 0i32),
            "SwitchOnGeneratorState" => (1, 2, None, 0),
            _ => return None,
        };
        let table_start = match ins.operands.get(start_idx)? {
            Operand::Idx(v) => *v as usize,
            _ => return None,
        };
        let table_size = match ins.operands.get(size_idx)? {
            Operand::Idx(v) => *v as usize,
            Operand::Imm(v) => *v as usize,
            _ => return None,
        };
        let case_base = match base_idx {
            Some(i) => match ins.operands.get(i)? {
                Operand::Imm(v) => *v as i32,
                Operand::Idx(v) => *v as i32,
                _ => return None,
            },
            None => base_fixed,
        };
        let pool = self
            .cache
            .slot_at(bca_id, self.bca_constant_pool_slot())
            .and_then(|v| v.as_ref())
            .and_then(|r| self.cache.ref_object(r))?;
        let mut out = Vec::new();
        for i in 0..table_size {
            // V8 迭代器跳过非 Smi 槽,但 case 值随槽位递增
            if let Some(Elem::Smi(v)) = self.cache.array_elem(pool, table_start + i) {
                // 同样走 GetAbsoluteOffset(含 Wide 前缀字节)
                let prefix = if ins.scale > 1 { 1 } else { 0 };
                out.push((case_base + i as i32, ins.offset + prefix + v as usize));
            }
        }
        Some(out)
    }

    /// 供 CLI 使用的公开入口。
    pub fn array_elem_public(&self, id: ObjId, index: usize) -> Option<Elem<'a>> {
        self.cache.array_elem(id, index)
    }

    /// parameter_count 是否直接是计数(13.x+)。
    pub fn parameter_count_direct(&self) -> bool {
        self.table.parameter_count.map(|c| c.direct).unwrap_or(false)
    }


    /// FixedArray 元素数。
    pub fn fixed_array_len(&self, id: ObjId) -> usize {
        self.cache.array_len(id)
    }

    /// FixedArray 元素展开(Smi / 引用,按元素序)。
    pub fn fixed_array_entries(&self, id: ObjId) -> Vec<String> {
        let len = self.fixed_array_len(id);
        (0..len)
            .map(|i| match self.cache.array_elem(id, i) {
                Some(Elem::Smi(v)) => v.to_string(),
                Some(Elem::Ref(r)) => self.describe_ref(&r),
                Some(Elem::Bytes(b)) => format!("<raw {}>", hex(b)),
                None => "<hole>".into(),
            })
            .collect()
    }

    /// FixedArray 的数值元素(Smi → Some,其余 → None),用于跳转表。
    pub fn fixed_array_smis(&self, id: ObjId) -> Vec<Option<i64>> {
        let len = self.fixed_array_len(id);
        (0..len)
            .map(|i| self.cache.array_elem(id, i).and_then(|e| e.as_smi()))
            .collect()
    }

    /// 引用 → 可读描述(对齐 V8 printer 的常量池样式)。
    pub fn describe_ref(&self, r: &Ref) -> String {
        match r {
            Ref::Object(id) => {
                let o = self.cache.obj(*id);
                match o.ty.name(self.table).as_ref() {
                    t if t.contains("String") => self
                        .string_value(*id)
                        .map(|s| format!("<String[{}]: #{} >", s.chars().count(), s))
                        .unwrap_or_else(|| "<String>".into()),
                    "SharedFunctionInfo" => {
                        format!("<SharedFunctionInfo {}>", self.sfi_name(*id))
                    }
                    "HeapNumber" => {
                        let v = self
                            .cache
                            .raw_at(*id, self.layout.tagged_size, 8)
                            .map(|d| f64::from_le_bytes(d.try_into().unwrap()))
                            .unwrap_or(f64::NAN);
                        format!("<HeapNumber {v}>")
                    }
                    "ScopeInfo" => "<ScopeInfo>".into(),
                    "FixedArray" | "FixedCOWArray" => format!("<FixedArray[{}]>", self.fixed_array_entries(*id).len()),
                    "ObjectBoilerplateDescription" => "<ObjectBoilerplateDescription>".into(),
                    "ArrayBoilerplateDescription" => "<ArrayBoilerplateDescription>".into(),
                    "ByteArray" | "EmptyByteArray" => "<ByteArray>".into(),
                    t if t.contains("BigInt") => self
                        .bigint_value(*id)
                        .map(|v| format!("<BigInt {v}>"))
                        .unwrap_or_else(|| "<BigInt>".into()),
                    other => format!("<{other}>"),
                }
            }
            Ref::Root(i) => {
                let name = self
                    .table
                    .roots
                    .get(*i)
                    .cloned()
                    .unwrap_or_else(|| format!("root#{i}"));
                match name.as_str() {
                    n if n.starts_with("String:") => format!("<String: {}>", &n[7..]),
                    n if n.starts_with("Symbol:") => format!("<Symbol: {}>", &n[7..]),
                    "undefined_value" => "<undefined>".into(),
                    "null_value" => "<null>".into(),
                    "true_value" => "<true>".into(),
                    "false_value" => "<false>".into(),
                    "the_hole_value" => "<the_hole>".into(),
                    "uninitialized_value" => "<uninitialized>".into(),
                    "empty_fixed_array" => "<EmptyFixedArray>".into(),
                    "empty_string" => "<String[0]: #>".into(),
                    other => format!("<{other}>"),
                }
            }
            Ref::Attached(0) => {
                let len = self.attached_source_len();
                format!("<String[{len}]: #(source placeholder)>")
            }
            Ref::Attached(i) => format!("<Attached({i})>"),
            Ref::RoRef(c, o) => format!("<ro:{c}/{o}>"),
        }
    }

    /// 源码占位字符串长度(来自头部 source_hash,由调用方注入)
    fn attached_source_len(&self) -> u32 {
        self.source_len
    }

    pub fn string_value(&self, id: ObjId) -> Option<String> {
        decode_string(self.cache, self.table, id)
    }

    pub fn bigint_value(&self, id: ObjId) -> Option<String> {
        // BigInt 布局(V8 `objects/bigint.{h,cc}` 核对):
        //   bit_field 是 int32(低 4 字节):bit0 = 符号(`sign()==true` 表示负),
        //   长度从 bit1 起(digit **个数**);digit 从偏移 2*ts 起,每位 ts 字节
        //   (`digit_t = uintptr_t`,压缩构建 4 字节 / 非压缩 8 字节),
        //   **digit 存绝对值**(`FromInt64` 里先取 absolute 再 set_64_bits)。
        //   负债就是"绝对值 + 符号位",不是补码。
        let ts = self.layout.tagged_size;
        let bf = self.cache.raw_at(id, ts, ts.min(8))?;
        let bf = u32::from_le_bytes(bf[..4].try_into().ok()?);
        let negative = bf & 1 == 1;
        let len = (bf >> 1) as usize;
        if len == 0 {
            return Some("0".into());
        }
        let bytes = self.cache.raw_at(id, 2 * ts, len * ts)?;
        let mut words: Vec<u64> = Vec::with_capacity(len);
        for chunk in bytes.chunks(ts) {
            words.push(match chunk.len() {
                4 => u32::from_le_bytes(chunk.try_into().ok()?) as u64,
                8 => u64::from_le_bytes(chunk.try_into().ok()?),
                _ => return None,
            });
        }
        // 十进制化:反复除以 1e9(不用 i128 —— 256 位的值塞进去会让移位按 128 取模、
        // 最高位落到符号位上,`-0x761f…n` 这类 4 位 digit 的**正数**会解成负数,
        // 渲染出 `--5981…n` 这种语法错)。
        let mut out: Vec<u32> = Vec::new();
        while words.iter().any(|&w| w != 0) {
            let mut rem: u128 = 0;
            for w in words.iter_mut().rev() {
                let cur = (rem << (8 * ts)) | (*w as u128);
                *w = (cur / 1_000_000_000u128) as u64;
                rem = cur % 1_000_000_000u128;
            }
            out.push(rem as u32);
        }
        let mut s = String::new();
        if negative {
            s.push('-');
        }
        s.push_str(&out.pop().unwrap_or(0).to_string());
        while let Some(c) = out.pop() {
            s.push_str(&format!("{c:09}"));
        }
        Some(s)
    }

    /// 供 CLI 注入源码长度(attached ref 0 的展示)
    pub fn with_source_len(mut self, len: u32) -> Self {
        self.source_len = len;
        self
    }
}



/// Ref → 名字字符串(字符串对象 / 根名字),供反编译与 ScopeInfo 读取复用。
/// 字符串解码(表驱动布局;`Disassembler::string_value` 与 `name_of_ref` 共用)。
pub fn decode_string(cache: &CodeCache<'_>, table: &VersionTable, id: ObjId) -> Option<String> {
    let obj = cache.obj(id);
    // 字符串布局:
    //   @0 map | @8 hash_field | @12 length | chars
    // 长度的**形态**随版本变:≤6.x 是 Smi(占一个 tagged 槽,字符区在 12+ts = 20),
    // 7.x 起是 int32(字符区在 16)。按 6.x 读成 int32 时长度恒为 0(Smi 的低半字为 0),
    // 于是所有字符串都变成空串 —— node8 的 SFI 名、全局名全丢。
    let len_off = table.string_length_offset.unwrap_or(12);
    let length = if table.string_length_smi {
        let ts = table.tagged_size as usize;
        let d = cache.raw_at(id, len_off, ts)?;
        if ts == 8 {
            (read_u64(d) >> 32) as u32 as usize
        } else {
            let raw = u32::from_le_bytes(d.try_into().ok()?);
            ((raw as i32) >> 1) as usize
        }
    } else {
        cache
            .raw_at(id, len_off, 4)
            .map(|d| u32::from_le_bytes(d.try_into().unwrap()) as usize)?
    };
    let is_one_byte = match obj.ty {
        crate::serializer::Ty::Str(crate::serializer::StrKind::OneByte) => true,
        crate::serializer::Ty::Str(crate::serializer::StrKind::TwoByte) => false,
        _ => obj.ty.name(table).contains("OneByte"),
    };
    let chars_off = table.string_chars_offset.unwrap_or(16);
    let d = cache.raw_at(id, chars_off, length)?;
    if is_one_byte {
        Some(String::from_utf8_lossy(d).into_owned())
    } else {
        let u16s: Vec<u16> = d
            .chunks(2)
            .map(|c| u16::from_le_bytes([c[0], *c.get(1).unwrap_or(&0)]))
            .collect();
        Some(String::from_utf16_lossy(&u16s))
    }
}

pub fn name_of_ref(cache: &CodeCache<'_>, table: &VersionTable, r: Ref) -> Option<String> {
    match r {
        Ref::Object(id) => {
            let o = cache.obj(id);
            if o.ty.is_string(table) {
                decode_string(cache, table, id)
            } else {
                None
            }
        }
        Ref::Root(i) => table.root_name(i).map(|n| {
            match n {
                // 这些 root 作为"名字"出现时应为空(CamelName 形态来自 roots.h 列表)
                "empty_string" | "EmptyString" | "undefined_value" | "UndefinedValue"
                | "uninitialized_value" | "UninitializedValue" | "the_hole_value"
                | "TheHoleValue" => String::new(),
                other => other
                    .strip_prefix("String:")
                    .or_else(|| other.strip_prefix("Symbol:"))
                    .unwrap_or(other)
                    .to_string(),
            }
        }),
        _ => None,
    }
}

fn read_u64(d: &[u8]) -> u64 {
    let mut v = 0u64;
    for (i, b) in d.iter().take(8).enumerate() {
        v |= (*b as u64) << (8 * i);
    }
    v
}

fn hex(d: &[u8]) -> String {
    d.iter().map(|b| format!("{b:02x}")).collect::<Vec<_>>().join("")
}

#[allow(dead_code)]
fn max_register(instrs: &[Instr]) -> Option<i32> {
    let mut max: Option<i32> = None;
    for ins in instrs {
        for op in &ins.operands {
            let idx = match op {
                Operand::Reg(i) => Some(*i),
                Operand::RegList { first, count } => Some(if *count > 0 {
                    first + (*count as i32) - 1
                } else {
                    *first
                }),
                _ => None,
            };
            if let Some(i) = idx {
                if i >= 0 {
                    max = Some(max.map_or(i, |m: i32| m.max(i)));
                }
            }
        }
    }
    max
}