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
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
mod config;
mod file_io;
mod memory;
use anyhow::{bail, Context, Result};
use byteorder::ByteOrder;
use clap::{Parser, Subcommand};
use config::Config;
use serde::Deserialize;
use std::fs;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process::Command;
#[derive(Debug, Deserialize)]
struct PartCategoriesFile {
categories: Vec<PartCategory>,
}
#[derive(Debug, Deserialize)]
struct PartCategory {
prefix: String,
category: i64,
#[serde(default)]
weapon_type: Option<String>,
#[serde(default)]
gear_type: Option<String>,
#[serde(default)]
manufacturer: Option<String>,
}
#[derive(Parser)]
#[command(name = "bl4")]
#[command(about = "Borderlands 4 Save Editor", long_about = None)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Decrypt a .sav file to YAML (uses stdin/stdout if paths not specified)
Decrypt {
/// Path to encrypted .sav file (uses stdin if not specified)
#[arg(short, long)]
input: Option<PathBuf>,
/// Path to output YAML file (uses stdout if not specified)
#[arg(short, long)]
output: Option<PathBuf>,
/// Steam ID for decryption (uses configured default if not provided)
#[arg(short, long)]
steam_id: Option<String>,
},
/// Encrypt a YAML file to .sav (uses stdin/stdout if paths not specified)
Encrypt {
/// Path to input YAML file (uses stdin if not specified)
#[arg(short, long)]
input: Option<PathBuf>,
/// Path to output .sav file (uses stdout if not specified)
#[arg(short, long)]
output: Option<PathBuf>,
/// Steam ID for encryption (uses configured default if not provided)
#[arg(short, long)]
steam_id: Option<String>,
},
/// Edit a save file in your $EDITOR
Edit {
/// Path to .sav file
#[arg(short, long)]
input: PathBuf,
/// Steam ID for decryption/encryption (uses configured default if not provided)
#[arg(short, long)]
steam_id: Option<String>,
/// Create backup before editing
#[arg(short, long, default_value_t = true)]
backup: bool,
},
/// Inspect a save file (decrypt and display info)
Inspect {
/// Path to .sav file
#[arg(short, long)]
input: PathBuf,
/// Steam ID for decryption (uses configured default if not provided)
#[arg(short, long)]
steam_id: Option<String>,
/// Show full YAML output
#[arg(short, long)]
full: bool,
},
/// Get specific values from a save file
Get {
/// Path to .sav file
#[arg(short, long)]
input: PathBuf,
/// Steam ID for decryption (uses configured default if not provided)
#[arg(short, long)]
steam_id: Option<String>,
/// YAML path query (e.g. "state.currencies.cash" or "state.experience[0].level")
query: Option<String>,
/// Show character level and XP
#[arg(long)]
level: bool,
/// Show currency (cash, eridium)
#[arg(long)]
money: bool,
/// Show character info (name, class, difficulty)
#[arg(long)]
info: bool,
/// Show all available data
#[arg(long)]
all: bool,
},
/// Set specific values in a save file
Set {
/// Path to .sav file
#[arg(short, long)]
input: PathBuf,
/// Steam ID for encryption/decryption (uses configured default if not provided)
#[arg(short, long)]
steam_id: Option<String>,
/// YAML path to modify (e.g. "state.currencies.cash" or "state.experience[0].level")
path: String,
/// Value to set (auto-detects numbers vs strings, unless --raw is used)
value: String,
/// Treat value as raw YAML (for complex/unknown structures)
#[arg(short, long)]
raw: bool,
/// Create backup before modifying
#[arg(short, long, default_value_t = true)]
backup: bool,
},
/// Configure default settings
Configure {
/// Set default Steam ID
#[arg(long)]
steam_id: Option<String>,
/// Show current configuration
#[arg(long)]
show: bool,
},
/// Decode an item serial number
Decode {
/// Item serial to decode (e.g. @Ugr$ZCm/&tH!t{KgK/Shxu>k)
serial: String,
/// Show detailed byte-by-byte breakdown
#[arg(short, long)]
verbose: bool,
/// Show bit-by-bit parsing debug output
#[arg(short, long)]
debug: bool,
/// Analyze first token bit structure for group ID research
#[arg(short, long)]
analyze: bool,
/// Path to parts database for resolving part names
#[arg(long, default_value = "share/manifest/parts_database.json")]
parts_db: PathBuf,
},
/// Query parts database - find parts for a weapon type
Parts {
/// Weapon name (e.g. "Jakobs Pistol", "Vladof SMG")
#[arg(short, long)]
weapon: Option<String>,
/// Category ID (e.g. 3 for Jakobs Pistol)
#[arg(short, long)]
category: Option<i64>,
/// List all categories
#[arg(short, long)]
list: bool,
/// Path to parts database
#[arg(long, default_value = "share/manifest/parts_database.json")]
parts_db: PathBuf,
},
/// Read/analyze game memory (live process or dump file)
Memory {
/// Use preload-based injection (requires game launched with LD_PRELOAD)
#[arg(long)]
preload: bool,
/// Read from memory dump file instead of live process (for offline analysis)
#[arg(long, short = 'd')]
dump: Option<PathBuf>,
/// Path to maps file for dump (optional, defaults to <dump>.maps)
#[arg(long)]
maps: Option<PathBuf>,
#[command(subcommand)]
action: MemoryAction,
},
/// Launch Borderlands 4 with instrumentation
Launch {
/// Skip confirmation prompt
#[arg(short = 'y', long)]
yes: bool,
},
/// Show info about a usmap file
UsmapInfo {
/// Path to usmap file
path: PathBuf,
},
/// Search usmap for struct/enum names
UsmapSearch {
/// Path to usmap file
path: PathBuf,
/// Search pattern (case-insensitive substring match)
pattern: String,
/// Show struct properties
#[arg(short, long)]
verbose: bool,
},
/// Extract part pools from the parts database (category groupings)
ExtractPartPools {
/// Input parts database JSON
#[arg(short, long, default_value = "share/manifest/parts_database.json")]
input: PathBuf,
/// Output part pools JSON
#[arg(short, long, default_value = "share/manifest/part_pools.json")]
output: PathBuf,
},
}
#[derive(Subcommand)]
enum MemoryAction {
/// Show info about the attached process
Info,
/// Discover UE5 structures (GNames, GUObjectArray)
Discover {
/// What to discover (gnames, guobjectarray, all)
#[arg(default_value = "all")]
target: String,
},
/// List UObjects by class name
Objects {
/// Class name to filter by (e.g. "RarityWeightData", "ItemPoolDef")
#[arg(short, long)]
class: Option<String>,
/// Maximum number of objects to show
#[arg(short, long, default_value = "20")]
limit: usize,
},
/// Dump usmap mappings file from live process
DumpUsmap {
/// Output path for usmap file
#[arg(short, long, default_value = "BL4.usmap")]
output: PathBuf,
},
/// Look up an FName by index
Fname {
/// FName index to look up
index: u32,
/// Show raw bytes at the FName entry (for debugging)
#[arg(long)]
debug: bool,
},
/// Search for an FName by string
FnameSearch {
/// String to search for in the FName pool
query: String,
},
/// Search for Class UClass by scanning for self-referential objects
FindClassUClass,
/// List all UClass instances in memory (uses discovered metaclass address)
ListUClasses {
/// Maximum number of classes to show (0 = all)
#[arg(short, long, default_value = "50")]
limit: usize,
/// Filter by class name pattern (case-insensitive)
#[arg(short, long)]
filter: Option<String>,
},
/// Enumerate UObjects from GUObjectArray
ListObjects {
/// Maximum number of objects to show
#[arg(short, long, default_value = "20")]
limit: usize,
/// Filter by class name pattern (case-insensitive)
#[arg(short = 'c', long)]
class_filter: Option<String>,
/// Filter by object name pattern (case-insensitive)
#[arg(short = 'n', long)]
name_filter: Option<String>,
/// Show statistics only (don't list individual objects)
#[arg(long)]
stats: bool,
},
/// Analyze dump file: discover UObject layout, FName pool, and UClass metaclass
AnalyzeDump,
/// List current inventory items
ListInventory,
/// Read a value from game memory
Read {
/// Memory address (hex, e.g. 0x7f1234567890)
address: String,
/// Number of bytes to read
#[arg(short, long, default_value = "64")]
size: usize,
},
/// Write bytes to game memory
Write {
/// Memory address (hex, e.g. 0x7f1234567890)
address: String,
/// Hex bytes to write (e.g. "90 90 90" for NOPs)
bytes: String,
},
/// Scan for a pattern in memory
Scan {
/// Hex pattern to search for (e.g. "48 8B 05 ?? ?? ?? ??")
pattern: String,
},
/// Patch a single instruction (replaces with NOPs or custom bytes)
Patch {
/// Memory address to patch (hex)
address: String,
/// Number of bytes to NOP out
#[arg(short, long)]
nop: Option<usize>,
/// Custom replacement bytes (hex, e.g. "EB 05" for short jump)
#[arg(short, long)]
bytes: Option<String>,
},
/// Apply template modifications (e.g. dropRate=max, dropRarity=legendary)
Apply {
/// Template assignments (e.g. "dropRate=max" "dropRarity=legendary")
#[arg(required = true)]
templates: Vec<String>,
},
/// List available injection templates
Templates,
/// Monitor the preload library log file
Monitor {
/// Path to log file
#[arg(short, long, default_value = "/tmp/bl4_preload.log")]
log_file: PathBuf,
/// Filter log entries by function name
#[arg(short, long)]
filter: Option<String>,
/// Only show entries from addresses in game code (not libraries)
#[arg(long)]
game_only: bool,
},
/// Search for a string in memory and dump context around matches
ScanString {
/// String to search for
query: String,
/// Bytes to show before the match
#[arg(short = 'B', long, default_value = "64")]
before: usize,
/// Bytes to show after the match
#[arg(short = 'A', long, default_value = "64")]
after: usize,
/// Maximum number of matches to show
#[arg(short, long, default_value = "10")]
limit: usize,
},
/// Extract part definitions from memory dump (searches for XXX_YY.part_* patterns)
DumpParts {
/// Output file for parts JSON
#[arg(short, long, default_value = "parts_dump.json")]
output: PathBuf,
},
/// Build parts database with Category/Index mappings
BuildPartsDb {
/// Input parts dump JSON (from dump-parts command)
#[arg(short, long, default_value = "share/manifest/parts_dump.json")]
input: PathBuf,
/// Output parts database JSON
#[arg(short, long, default_value = "share/manifest/parts_database.json")]
output: PathBuf,
/// Part categories mapping JSON (prefix -> category ID)
#[arg(short, long, default_value = "share/manifest/part_categories.json")]
categories: PathBuf,
},
/// Extract part definitions from UObjects with authoritative Category/Index from SerialIndex
ExtractParts {
/// Output file for extracted parts with categories
#[arg(short, long, default_value = "parts_with_categories.json")]
output: PathBuf,
},
/// Find objects matching a name pattern to discover their class
FindObjectsByPattern {
/// Name pattern to search for (e.g. ".part_")
pattern: String,
/// Maximum number of results
#[arg(short, long, default_value = "10")]
limit: usize,
},
/// Generate an object map JSON for fast lookups on subsequent runs
GenerateObjectMap {
/// Output file for object map JSON
#[arg(short, long)]
output: Option<PathBuf>,
},
}
/// Helper function to get Steam ID from argument or config
fn get_steam_id(provided: Option<String>) -> Result<String> {
if let Some(id) = provided {
return Ok(id);
}
let config = Config::load()?;
config.get_steam_id().map(String::from).context(
"Steam ID not provided. Run 'bl4 configure --steam-id YOUR_STEAM_ID' to set a default.",
)
}
/// Helper function to update backup metadata after editing a save file
fn update_backup_metadata(input: &std::path::Path) -> Result<()> {
let (_, metadata_path) = bl4::backup::backup_paths(input);
bl4::update_after_edit(input, &metadata_path).context("Failed to update backup metadata")
}
fn main() -> Result<()> {
let cli = Cli::parse();
match cli.command {
Commands::Configure { steam_id, show } => {
let mut config = Config::load()?;
if show {
if let Some(id) = config.get_steam_id() {
println!("Steam ID: {}", id);
} else {
println!("No Steam ID configured");
}
if let Ok(path) = Config::config_path() {
println!("Config file: {}", path.display());
}
return Ok(());
}
if let Some(id) = steam_id {
config.set_steam_id(id.clone());
config.save()?;
println!("Steam ID configured: {}", id);
if let Ok(path) = Config::config_path() {
println!("Config saved to: {}", path.display());
}
} else {
println!("Usage: bl4 configure --steam-id YOUR_STEAM_ID");
println!(" or: bl4 configure --show");
println!();
println!("Note: Borderlands 4 uses your Steam ID to encrypt saves.");
println!(" Find it in the top left of your Steam account page.");
}
}
Commands::Decrypt {
input,
output,
steam_id,
} => {
let steam_id = get_steam_id(steam_id)?;
let encrypted = file_io::read_input(input.as_deref())?;
let yaml_data =
bl4::decrypt_sav(&encrypted, &steam_id).context("Failed to decrypt save file")?;
file_io::write_output(output.as_deref(), &yaml_data)?;
}
Commands::Encrypt {
input,
output,
steam_id,
} => {
let steam_id = get_steam_id(steam_id)?;
let yaml_data = file_io::read_input(input.as_deref())?;
let encrypted =
bl4::encrypt_sav(&yaml_data, &steam_id).context("Failed to encrypt YAML data")?;
file_io::write_output(output.as_deref(), &encrypted)?;
}
Commands::Edit {
input,
steam_id,
backup,
} => {
let steam_id = get_steam_id(steam_id)?;
// Get editor from environment and parse it
let editor_str = std::env::var("EDITOR").unwrap_or_else(|_| "vim".to_string());
let editor_parts: Vec<&str> = editor_str.split_whitespace().collect();
let (editor, editor_args) = if editor_parts.is_empty() {
("vim", vec![])
} else {
(editor_parts[0], editor_parts[1..].to_vec())
};
// Smart backup if requested
if backup {
let _ = bl4::smart_backup(&input).context("Failed to manage backup")?;
}
// Decrypt to temp file
let encrypted =
fs::read(&input).with_context(|| format!("Failed to read {}", input.display()))?;
let yaml_data =
bl4::decrypt_sav(&encrypted, &steam_id).context("Failed to decrypt save file")?;
let temp_path = input.with_extension("yaml.tmp");
let abs_temp_path = std::fs::canonicalize(temp_path.parent().unwrap())
.unwrap()
.join(temp_path.file_name().unwrap());
fs::write(&abs_temp_path, &yaml_data).with_context(|| {
format!("Failed to write temp file {}", abs_temp_path.display())
})?;
// Open editor
let mut cmd = Command::new(editor);
cmd.args(&editor_args);
cmd.arg(&abs_temp_path);
let status = cmd
.status()
.with_context(|| format!("Failed to launch editor: {}", editor))?;
if !status.success() {
bail!("Editor exited with non-zero status");
}
// Re-encrypt
let modified_yaml =
fs::read(&abs_temp_path).context("Failed to read modified temp file")?;
let encrypted = bl4::encrypt_sav(&modified_yaml, &steam_id)
.context("Failed to encrypt modified YAML")?;
fs::write(&input, &encrypted)
.with_context(|| format!("Failed to write {}", input.display()))?;
// Clean up temp file
fs::remove_file(&abs_temp_path).context("Failed to remove temp file")?;
// Update hash tracking after edit
if backup {
update_backup_metadata(&input)?;
}
}
Commands::Inspect {
input,
steam_id,
full,
} => {
let steam_id = get_steam_id(steam_id)?;
let encrypted =
fs::read(&input).with_context(|| format!("Failed to read {}", input.display()))?;
let yaml_data =
bl4::decrypt_sav(&encrypted, &steam_id).context("Failed to decrypt save file")?;
if full {
// Print entire YAML
println!("{}", String::from_utf8_lossy(&yaml_data));
} else {
// Parse and show basic info
let save: serde_yaml::Value =
serde_yaml::from_slice(&yaml_data).context("Failed to parse YAML")?;
println!("Save file structure:");
if let Some(obj) = save.as_mapping() {
for key in obj.keys() {
println!(" - {}", key.as_str().unwrap_or("?"));
}
}
println!("\nUse --full to see complete YAML");
}
}
Commands::Get {
input,
steam_id,
query,
level,
money,
info,
all,
} => {
let steam_id = get_steam_id(steam_id)?;
let encrypted =
fs::read(&input).with_context(|| format!("Failed to read {}", input.display()))?;
let yaml_data =
bl4::decrypt_sav(&encrypted, &steam_id).context("Failed to decrypt save file")?;
let save = bl4::SaveFile::from_yaml(&yaml_data).context("Failed to parse save file")?;
// Handle query path if provided
if let Some(query_path) = query {
let result = save.get(&query_path).context("Query failed")?;
println!("{}", serde_yaml::to_string(&result)?);
return Ok(());
}
let show_all = all || (!level && !money && !info);
// Extract character info
if show_all || info {
if let Some(name) = save.get_character_name() {
println!("Character: {}", name);
}
if let Some(class) = save.get_character_class() {
println!("Class: {}", class);
}
if let Some(diff) = save.get_difficulty() {
println!("Difficulty: {}", diff);
}
if show_all || info {
println!();
}
}
// Extract level/XP info
if show_all || level {
if let Some((lvl, pts)) = save.get_character_level() {
println!("Character Level: {} ({} XP)", lvl, pts);
}
if let Some((lvl, pts)) = save.get_specialization_level() {
println!("Specialization Level: {} ({} XP)", lvl, pts);
}
if show_all || level {
println!();
}
}
// Extract currency info
if show_all || money {
if let Some(cash) = save.get_cash() {
println!("Cash: {}", cash);
}
if let Some(eridium) = save.get_eridium() {
println!("Eridium: {}", eridium);
}
}
}
Commands::Set {
input,
steam_id,
path,
value,
raw,
backup,
} => {
let steam_id = get_steam_id(steam_id)?;
// Smart backup if requested
if backup {
let _ = bl4::smart_backup(&input).context("Failed to manage backup")?;
}
// Read and decrypt
let encrypted =
fs::read(&input).with_context(|| format!("Failed to read {}", input.display()))?;
let yaml_data =
bl4::decrypt_sav(&encrypted, &steam_id).context("Failed to decrypt save file")?;
let mut save =
bl4::SaveFile::from_yaml(&yaml_data).context("Failed to parse save file")?;
// Parse and set the new value
if raw {
eprintln!("Setting {} = {} (raw YAML)", path, value);
save.set_raw(&path, &value)
.context("Failed to set raw value")?;
} else {
let new_value = bl4::SaveFile::parse_value(&value);
eprintln!("Setting {} = {}", path, value);
save.set(&path, new_value).context("Failed to set value")?;
}
// Re-serialize to YAML
let modified_yaml = save.to_yaml().context("Failed to serialize YAML")?;
// Re-encrypt
let encrypted = bl4::encrypt_sav(&modified_yaml, &steam_id)
.context("Failed to encrypt save file")?;
// Write back
fs::write(&input, &encrypted)
.with_context(|| format!("Failed to write {}", input.display()))?;
// Update hash tracking after edit
if backup {
update_backup_metadata(&input)?;
}
}
Commands::Decode {
serial,
verbose,
debug,
analyze,
parts_db,
} => {
let item = bl4::ItemSerial::decode(&serial).context("Failed to decode serial")?;
println!("Serial: {}", item.original);
println!(
"Item type: {} ({})",
item.item_type,
item.item_type_description()
);
// Show weapon info based on format type
if let Some((mfr, weapon_type)) = item.weapon_info() {
// VarInt-first format: first VarInt encodes manufacturer + weapon type
println!("Weapon: {} {}", mfr, weapon_type);
} else if let Some(group_id) = item.part_group_id() {
// VarBit-first format: use Part Group ID
let category_name = bl4::category_name(group_id).unwrap_or("Unknown");
println!("Category: {} ({})", category_name, group_id);
}
// Show raw manufacturer ID if we couldn't resolve it
if item.weapon_info().is_none() {
if let Some(mfr) = item.manufacturer_name() {
println!("Manufacturer: {}", mfr);
} else if let Some(mfr_id) = item.manufacturer {
println!("Manufacturer ID: {} (unknown)", mfr_id);
}
}
// Show level and seed for VarInt-first format
if let Some(level) = item.level {
println!("Level: {}", level);
}
if let Some(seed) = item.seed {
println!("Seed: {}", seed);
}
println!("Decoded bytes: {}", item.raw_bytes.len());
println!("Hex: {}", item.hex_dump());
println!("Tokens: {}", item.format_tokens());
// Try to resolve part names from database
// Get category from either VarBit-first format or VarInt-first format
let category: Option<i64> = item.part_group_id().or_else(|| {
// Try to derive from VarInt-first weapon info
item.weapon_info().and_then(|(mfr, wtype)| {
// Map short weapon type to full name
let weapon_full = match wtype {
"AR" => "Assault Rifle",
"SMG" => "SMG",
"SR" => "Sniper",
"PS" => "Pistol",
"SG" => "Shotgun",
"HW" => "Heavy",
_ => wtype,
};
let search = format!("{} {}", mfr, weapon_full).to_lowercase();
// Search known categories
for cat in 1..=500 {
if let Some(name) = bl4::category_name(cat) {
if name.to_lowercase() == search {
return Some(cat);
}
}
}
None
})
});
// Resolve part names if we have a category and parts database
let parts = item.parts();
if let (Some(category), false) = (category, parts.is_empty()) {
#[derive(Debug, Deserialize)]
struct PartsDb {
parts: Vec<PartDbEntry>,
}
#[derive(Debug, Deserialize)]
struct PartDbEntry {
name: String,
category: i64,
index: i64,
}
if let Ok(db_content) = fs::read_to_string(&parts_db) {
if let Ok(db) = serde_json::from_str::<PartsDb>(&db_content) {
let lookup: std::collections::HashMap<(i64, i64), &str> = db
.parts
.iter()
.map(|p| ((p.category, p.index), p.name.as_str()))
.collect();
println!("\nResolved parts:");
for (part_index, values) in &parts {
let idx_i64 = *part_index as i64;
let extra = if values.is_empty() {
String::new()
} else {
format!(" (values: {:?})", values)
};
if let Some(name) = lookup.get(&(category, idx_i64)) {
println!(" {}{}", name, extra);
} else {
println!(" [unknown part index {}]{}", part_index, extra);
}
}
}
}
}
if verbose {
println!("\n{}", item.detailed_dump());
}
if debug {
println!("\nDebug parsing:");
bl4::serial::parse_tokens_debug(&item.raw_bytes);
}
if analyze {
// Analyze first token for group ID research
use bl4::serial::Token;
if let Some(first_token) = item.tokens.first() {
let value = match first_token {
Token::VarInt(v) => Some((*v, "VarInt")),
Token::VarBit(v) => Some((*v, "VarBit")),
_ => None,
};
if let Some((value, token_type)) = value {
println!("\n=== First Token Analysis ===");
println!("Type: {}", token_type);
println!("Value: {} (decimal)", value);
println!("Hex: 0x{:x}", value);
println!("Binary: {:024b}", value);
println!();
// Decode Part Group ID based on item type
println!("Part Group ID decoding:");
match item.item_type {
'r' | 'a'..='d' | 'f' | 'g' | 'v'..='z' => {
// Weapons: group_id = first_token / 8192
let group_id = value / 8192;
let offset = value % 8192;
println!(" Formula: group_id = value / 8192 (weapons)");
println!(" Group ID: {} (offset {})", group_id, offset);
// Use the authoritative category_name function from parts.rs
let group_name =
bl4::category_name(group_id as i64).unwrap_or("Unknown");
println!(" Identified: {}", group_name);
}
'e' => {
// Equipment: group_id = first_token / 384
let group_id = value / 384;
let offset = value % 384;
println!(" Formula: group_id = value / 384 (equipment)");
println!(" Group ID: {} (offset {})", group_id, offset);
// Use the authoritative category_name function from parts.rs
let group_name = bl4::category_name(group_id as i64)
.unwrap_or("Unknown Equipment");
println!(" Identified: {}", group_name);
}
'u' => {
// Utility items - formula TBD
println!(" Utility items - encoding formula not yet determined");
println!(" Raw value: {}", value);
}
'!' | '#' => {
// Class mods - formula TBD
println!(" Class mods - encoding formula not yet determined");
println!(" Raw value: {}", value);
}
_ => {
println!(
" Unknown item type '{}' - encoding formula not determined",
item.item_type
);
}
}
println!();
println!("Bit split analysis (for research):");
for split in [8, 10, 12, 13, 14] {
let high = value >> split;
let low = value & ((1 << split) - 1);
println!(" Split at bit {:2}: high={:6} low={:6}", split, high, low);
}
} else {
println!("\n=== First Token Analysis ===");
println!("First token is not numeric: {:?}", first_token);
}
}
}
}
Commands::Parts {
weapon,
category,
list,
parts_db,
} => {
// Load parts database
let db_content = fs::read_to_string(&parts_db)
.with_context(|| format!("Failed to read parts database: {:?}", parts_db))?;
#[derive(Debug, Deserialize)]
struct PartsDatabase {
parts: Vec<PartEntry>,
}
#[derive(Debug, Deserialize)]
struct PartEntry {
name: String,
category: i64,
index: i64,
}
let db: PartsDatabase =
serde_json::from_str(&db_content).context("Failed to parse parts database")?;
// Build category -> parts mapping
let mut by_category: std::collections::BTreeMap<i64, Vec<&PartEntry>> =
std::collections::BTreeMap::new();
for part in &db.parts {
by_category.entry(part.category).or_default().push(part);
}
if list {
// List all categories
println!("Available categories:");
println!();
for (&cat_id, parts) in &by_category {
let cat_name = bl4::category_name(cat_id).unwrap_or("Unknown");
println!(" {:3}: {} ({} parts)", cat_id, cat_name, parts.len());
}
println!();
println!(
"Total: {} categories, {} parts",
by_category.len(),
db.parts.len()
);
return Ok(());
}
// Find target category
let target_cat: Option<i64> = if let Some(cat) = category {
Some(cat)
} else if let Some(ref wname) = weapon {
// Search for category by weapon name
let search = wname.to_lowercase();
let mut found = None;
for &cat_id in by_category.keys() {
if let Some(name) = bl4::category_name(cat_id) {
if name.to_lowercase().contains(&search) {
if found.is_some() {
println!("Multiple matches for '{}'. Please be more specific or use -c <category_id>", wname);
for &c in by_category.keys() {
if let Some(n) = bl4::category_name(c) {
if n.to_lowercase().contains(&search) {
println!(" {:3}: {}", c, n);
}
}
}
return Ok(());
}
found = Some(cat_id);
}
}
}
found
} else {
None
};
if let Some(cat_id) = target_cat {
let cat_name = bl4::category_name(cat_id).unwrap_or("Unknown");
let parts = by_category.get(&cat_id);
println!("Parts for {} (category {}):", cat_name, cat_id);
println!();
if let Some(parts) = parts {
// Group by part type (barrel, grip, mag, etc.)
let mut by_type: std::collections::BTreeMap<String, Vec<&&PartEntry>> =
std::collections::BTreeMap::new();
for part in parts {
// Extract part type from name (e.g., "DAD_PS.part_barrel_01" -> "barrel")
let part_type = part
.name
.split(".part_")
.nth(1)
.and_then(|s| s.split('_').next())
.unwrap_or("other")
.to_string();
by_type.entry(part_type).or_default().push(part);
}
for (ptype, type_parts) in &by_type {
println!(" {} ({} variants):", ptype, type_parts.len());
for part in type_parts {
println!(" [{}] {}", part.index, part.name);
}
println!();
}
println!("Total: {} parts", parts.len());
} else {
println!(" No parts found for this category");
}
} else {
println!("Usage: bl4 parts --weapon <name> OR --category <id> OR --list");
println!();
println!("Examples:");
println!(" bl4 parts --list # List all categories");
println!(" bl4 parts --weapon 'Jakobs' # Find Jakobs weapons");
println!(" bl4 parts --category 3 # Show parts for category 3");
}
}
Commands::Memory {
preload,
dump,
maps,
action,
} => {
// Handle commands that don't require process attachment first
match action {
MemoryAction::Templates => {
println!("Available injection templates:");
println!();
println!(" dropRate=<value> - Modify drop rate probability");
println!(" Values: max, high, normal, low");
println!();
println!(" dropRarity=<value> - Bias loot toward specific rarity");
println!(" Values: legendary, epic, rare, uncommon, common");
println!();
println!(" luck=<value> - Set luck modifier");
println!(" Values: max, high, normal");
println!();
println!("Example usage:");
println!(" bl4 inject apply dropRate=max dropRarity=legendary");
println!(" bl4 inject --preload apply dropRate=max (preload mode)");
println!();
println!("Note: Without --preload, templates require finding memory");
println!(" addresses at runtime. Use 'bl4 inject scan' to locate");
println!(" the relevant game data first.");
println!();
println!(" With --preload, modifications work via the LD_PRELOAD");
println!(" library and affect RNG at the syscall level.");
return Ok(());
}
MemoryAction::BuildPartsDb {
ref input,
ref output,
ref categories,
} => {
// This command doesn't need memory access - just reads/writes JSON
println!("Building parts database from {}...", input.display());
println!("Loading categories from {}...", categories.display());
// Load part categories from JSON file
let categories_json = std::fs::read_to_string(categories)
.context("Failed to read part categories file")?;
let categories_file: PartCategoriesFile =
serde_json::from_str(&categories_json)
.context("Failed to parse part categories JSON")?;
// Convert to internal format (prefix, category_id, description)
let known_groups: Vec<(String, i64, String)> = categories_file
.categories
.into_iter()
.map(|cat| {
let description = if let Some(wt) = &cat.weapon_type {
if let Some(mfr) = &cat.manufacturer {
format!("{} {}", mfr, wt)
} else {
wt.clone()
}
} else if let Some(gt) = &cat.gear_type {
if let Some(mfr) = &cat.manufacturer {
format!("{} {}", mfr, gt)
} else {
gt.clone()
}
} else {
cat.prefix.clone()
};
(cat.prefix, cat.category, description)
})
.collect();
println!("Loaded {} category mappings", known_groups.len());
let parts_json =
std::fs::read_to_string(input).context("Failed to read parts dump file")?;
let mut parts_by_prefix: std::collections::BTreeMap<String, Vec<String>> =
std::collections::BTreeMap::new();
let mut current_prefix = String::new();
let mut in_array = false;
for line in parts_json.lines() {
let trimmed = line.trim();
if trimmed.starts_with('"') && trimmed.contains("\": [") {
if let Some(end_quote) = trimmed[1..].find('"') {
current_prefix = trimmed[1..end_quote + 1].to_string();
in_array = true;
parts_by_prefix.insert(current_prefix.clone(), Vec::new());
}
} else if in_array && trimmed.starts_with('"') && !trimmed.contains(": [") {
let name = trimmed
.trim_end_matches(',')
.trim_end_matches('"')
.trim_start_matches('"')
.to_string();
if !name.is_empty() {
if let Some(parts) = parts_by_prefix.get_mut(¤t_prefix) {
parts.push(name);
}
}
} else if trimmed == "]" || trimmed == "]," {
in_array = false;
}
}
let mut db_entries: Vec<(i64, i16, String, String)> = Vec::new();
for (prefix, category, description) in &known_groups {
if let Some(parts) = parts_by_prefix.get(prefix) {
for (idx, part_name) in parts.iter().enumerate() {
db_entries.push((
*category,
idx as i16,
part_name.clone(),
description.clone(),
));
}
}
}
let known_prefixes: std::collections::HashSet<&str> =
known_groups.iter().map(|(p, _, _)| p.as_str()).collect();
for (prefix, parts) in &parts_by_prefix {
if !known_prefixes.contains(prefix.as_str()) {
for (idx, part_name) in parts.iter().enumerate() {
db_entries.push((
-1,
idx as i16,
part_name.clone(),
format!("{} (unmapped)", prefix),
));
}
}
}
let mut json = String::from("{\n \"version\": 1,\n \"parts\": [\n");
for (i, (category, index, name, group)) in db_entries.iter().enumerate() {
let escaped_name = name.replace('\\', "\\\\").replace('"', "\\\"");
let escaped_group = group.replace('\\', "\\\\").replace('"', "\\\"");
json.push_str(&format!(
" {{\"category\": {}, \"index\": {}, \"name\": \"{}\", \"group\": \"{}\"}}",
category, index, escaped_name, escaped_group
));
if i < db_entries.len() - 1 {
json.push(',');
}
json.push('\n');
}
json.push_str(" ],\n \"categories\": {\n");
let mut category_counts: std::collections::BTreeMap<i64, (usize, String)> =
std::collections::BTreeMap::new();
for (category, _, _, group) in &db_entries {
let entry = category_counts
.entry(*category)
.or_insert((0, group.clone()));
entry.0 += 1;
}
let cat_count = category_counts.len();
for (i, (category, (count, name))) in category_counts.iter().enumerate() {
let escaped = name.replace('\\', "\\\\").replace('"', "\\\"");
json.push_str(&format!(
" \"{}\": {{\"count\": {}, \"name\": \"{}\"}}",
category, count, escaped
));
if i < cat_count - 1 {
json.push(',');
}
json.push('\n');
}
json.push_str(" }\n}\n");
std::fs::write(output, &json)?;
println!(
"Built parts database with {} entries across {} categories",
db_entries.len(),
category_counts.len()
);
println!("Written to: {}", output.display());
return Ok(());
}
MemoryAction::ExtractParts { ref output } => {
// This command works with both dump files and live memory
let source: Box<dyn memory::MemorySource> = match dump {
Some(ref p) => {
println!("Extracting part definitions from dump...");
Box::new(memory::DumpFile::open(p)?)
}
None => {
println!("Extracting part definitions from live process...");
let proc = memory::Bl4Process::attach()
.context("Failed to attach to Borderlands 4 process")?;
Box::new(proc)
}
};
// Use the new FName array pattern extraction
// This method scans for 0xFFFFFFFF markers in part registration arrays,
// then follows pointers to read GbxSerialNumberIndex at UObject+0x20
let parts = memory::extract_parts_from_fname_arrays(source.as_ref())?;
println!("Found {} part definitions", parts.len());
// Group by category for summary
let mut by_category: std::collections::BTreeMap<
i64,
Vec<&memory::PartDefinition>,
> = std::collections::BTreeMap::new();
for part in &parts {
by_category.entry(part.category).or_default().push(part);
}
println!("\nCategories found:");
for (category, cat_parts) in &by_category {
let max_idx = cat_parts.iter().map(|p| p.index).max().unwrap_or(0);
println!(
" Category {:3}: {:3} parts (max index: {})",
category,
cat_parts.len(),
max_idx
);
}
// Write output JSON
let mut json = String::from("{\n \"parts\": [\n");
for (i, part) in parts.iter().enumerate() {
let escaped_name = part.name.replace('\\', "\\\\").replace('"', "\\\"");
json.push_str(&format!(
" {{\"name\": \"{}\", \"category\": {}, \"index\": {}}}",
escaped_name, part.category, part.index
));
if i < parts.len() - 1 {
json.push(',');
}
json.push('\n');
}
json.push_str(" ],\n \"summary\": {\n");
let cat_count = by_category.len();
for (i, (category, cat_parts)) in by_category.iter().enumerate() {
json.push_str(&format!(" \"{}\": {}", category, cat_parts.len()));
if i < cat_count - 1 {
json.push(',');
}
json.push('\n');
}
json.push_str(" }\n}\n");
std::fs::write(output, &json)?;
println!("\nWritten to: {}", output.display());
return Ok(());
}
MemoryAction::FindObjectsByPattern { ref pattern, limit } => {
// This command requires a memory dump
let dump_path = match dump {
Some(ref p) => p.clone(),
None => bail!(
"FindObjectsByPattern requires a memory dump file. Use --dump <path>"
),
};
println!("Searching for objects matching '{}'...", pattern);
let source: Box<dyn memory::MemorySource> =
Box::new(memory::DumpFile::open(&dump_path)?);
// Discover GUObjectArray
println!("Discovering GNames pool...");
let gnames = memory::discover_gnames(source.as_ref())?;
println!(" GNames at: {:#x}", gnames.address);
println!("Discovering GUObjectArray...");
let guobjects =
memory::discover_guobject_array(source.as_ref(), gnames.address)?;
println!(" GUObjectArray at: {:#x}", guobjects.address);
println!(" NumElements: {}", guobjects.num_elements);
// Find objects
let results = memory::find_objects_by_pattern(
source.as_ref(),
&guobjects,
pattern,
limit,
)?;
println!("\nResults:");
for (name, class_name, class_ptr) in &results {
println!(" '{}' (class: {} @ {:#x})", name, class_name, class_ptr);
}
return Ok(());
}
MemoryAction::GenerateObjectMap { ref output } => {
// This command requires a memory dump
let dump_path = match dump {
Some(ref p) => p.clone(),
None => bail!(
"GenerateObjectMap requires a memory dump file. Use --dump <path>"
),
};
// Default output path is next to the dump file
let output_path = output.clone().unwrap_or_else(|| {
let mut p = dump_path.clone();
p.set_extension("objects.json");
p
});
println!("Generating object map from {}...", dump_path.display());
let source: Box<dyn memory::MemorySource> =
Box::new(memory::DumpFile::open(&dump_path)?);
// Discover GUObjectArray
println!("Discovering GNames pool...");
let gnames = memory::discover_gnames(source.as_ref())?;
println!(" GNames at: {:#x}", gnames.address);
println!("Discovering GUObjectArray...");
let guobjects =
memory::discover_guobject_array(source.as_ref(), gnames.address)?;
println!(" GUObjectArray at: {:#x}", guobjects.address);
println!(" NumElements: {}", guobjects.num_elements);
// Generate object map
let map = memory::generate_object_map(source.as_ref(), &guobjects)?;
// Write JSON output
let mut json = String::from("{\n");
let class_count = map.len();
for (i, (class_name, objects)) in map.iter().enumerate() {
let escaped_class = class_name.replace('\\', "\\\\").replace('"', "\\\"");
json.push_str(&format!(" \"{}\": [\n", escaped_class));
for (j, obj) in objects.iter().enumerate() {
let escaped_name = obj.name.replace('\\', "\\\\").replace('"', "\\\"");
json.push_str(&format!(
" {{\"name\": \"{}\", \"address\": \"{:#x}\", \"class_address\": \"{:#x}\"}}",
escaped_name, obj.address, obj.class_address
));
if j < objects.len() - 1 {
json.push(',');
}
json.push('\n');
}
json.push_str(" ]");
if i < class_count - 1 {
json.push(',');
}
json.push('\n');
}
json.push_str("}\n");
std::fs::write(&output_path, &json)?;
println!("Object map written to: {}", output_path.display());
println!(
" {} classes, {} total objects",
map.len(),
map.values().map(|v| v.len()).sum::<usize>()
);
return Ok(());
}
_ => {}
}
// Preload mode - communicate with the preload library via environment/signals
if preload {
match action {
MemoryAction::Apply { templates } => {
// Find preload library path
let exe_dir = std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|p| p.to_path_buf()));
let lib_path = exe_dir
.as_ref()
.map(|d| d.join("libbl4_preload.so"))
.filter(|p| p.exists())
.or_else(|| {
let p = PathBuf::from("target/release/libbl4_preload.so");
if p.exists() {
Some(std::fs::canonicalize(p).unwrap_or_default())
} else {
None
}
});
let lib_path = match lib_path {
Some(p) => p,
None => {
bail!(
"Preload library not found. Build it first:\n \
cargo build --release -p bl4-preload"
);
}
};
// Parse templates into env vars
let mut env_vars = Vec::new();
for template in &templates {
let parts: Vec<&str> = template.splitn(2, '=').collect();
if parts.len() != 2 {
eprintln!(
"Invalid template format: {} (expected key=value)",
template
);
continue;
}
let key = parts[0].to_lowercase();
let value = parts[1].to_lowercase();
match key.as_str() {
"droprate" | "droprarity" => {
// Map to BL4_DROP_BIAS
let bias = match value.as_str() {
"max" | "legendary" => "max",
"high" | "epic" => "high",
"normal" => "", // no bias
"low" | "uncommon" => "low",
"min" | "common" => "min",
_ => {
eprintln!("Unknown value for {}: {}", key, value);
continue;
}
};
if !bias.is_empty() {
env_vars.push(format!("BL4_RNG_BIAS={}", bias));
}
}
"luck" => {
let bias = match value.as_str() {
"max" => "max",
"high" => "high",
"normal" => "",
_ => {
eprintln!("Unknown value for luck: {}", value);
continue;
}
};
if !bias.is_empty() {
env_vars.push(format!("BL4_RNG_BIAS={}", bias));
}
}
_ => {
eprintln!("Unknown template: {}", key);
}
}
}
// Deduplicate env vars
env_vars.sort();
env_vars.dedup();
if env_vars.is_empty() {
println!("LD_PRELOAD={} %command%", lib_path.display());
} else {
println!(
"LD_PRELOAD={} {} %command%",
lib_path.display(),
env_vars.join(" ")
);
}
return Ok(());
}
MemoryAction::Monitor { .. } => {
// Monitor works the same in preload mode, fall through
// This is handled below in the main match
}
_ => {
bail!(
"This command is not available in --preload mode. \
Remove --preload to use direct memory injection."
);
}
}
}
// Commands that require memory access (live process or dump file)
// Create memory source based on options
let (process, dump_file): (Option<memory::Bl4Process>, Option<memory::DumpFile>) =
if let Some(dump_path) = &dump {
// Using dump file for offline analysis
let dump = if let Some(ref maps_path) = maps {
memory::DumpFile::open_with_maps(dump_path, maps_path)
.context("Failed to open dump file with maps")?
} else {
memory::DumpFile::open(dump_path).context("Failed to open dump file")?
};
(None, Some(dump))
} else {
// Attach to live process
let proc = memory::Bl4Process::attach()
.context("Failed to attach to Borderlands 4 process")?;
(Some(proc), None)
};
// Helper macro to get memory source
macro_rules! mem_source {
() => {
if let Some(ref p) = process {
p as &dyn memory::MemorySource
} else if let Some(ref d) = dump_file {
d as &dyn memory::MemorySource
} else {
unreachable!()
}
};
}
match action {
MemoryAction::Templates => unreachable!(),
MemoryAction::BuildPartsDb { .. } => unreachable!(), // Handled above before process attach
MemoryAction::ExtractParts { .. } => unreachable!(), // Handled above with dump file
MemoryAction::FindObjectsByPattern { .. } => unreachable!(), // Handled above with dump file
MemoryAction::GenerateObjectMap { .. } => unreachable!(), // Handled above with dump file
MemoryAction::Info => {
if let Some(ref proc) = process {
println!("{}", proc.info());
} else {
println!("Dump file mode - no live process info available");
println!(" Dump: {:?}", dump.as_ref().unwrap());
let source = mem_source!();
println!(" Regions: {}", source.regions().len());
}
}
MemoryAction::Discover { target } => {
let source = mem_source!();
match target.to_lowercase().as_str() {
"gnames" | "all" => {
println!("Searching for GNames pool...");
match memory::discover_gnames(source) {
Ok(gnames) => {
println!("GNames found at: {:#x}", gnames.address);
println!("\nSample names:");
for (idx, name) in &gnames.sample_names {
println!(" [{}] {}", idx, name);
}
if target == "all" {
println!("\nSearching for GUObjectArray...");
match memory::discover_guobject_array(
source,
gnames.address,
) {
Ok(arr) => {
println!(
"GUObjectArray found at: {:#x}",
arr.address
);
println!(" Objects ptr: {:#x}", arr.objects_ptr);
println!(" NumElements: {}", arr.num_elements);
println!(" MaxElements: {}", arr.max_elements);
}
Err(e) => {
eprintln!("GUObjectArray not found: {}", e);
}
}
}
}
Err(e) => {
eprintln!("GNames not found: {}", e);
}
}
}
"guobjectarray" => {
// First we need GNames
println!("Searching for GNames pool first...");
match memory::discover_gnames(source) {
Ok(gnames) => {
println!("GNames at: {:#x}", gnames.address);
println!("\nSearching for GUObjectArray...");
match memory::discover_guobject_array(source, gnames.address) {
Ok(arr) => {
println!("GUObjectArray found at: {:#x}", arr.address);
println!(" Objects ptr: {:#x}", arr.objects_ptr);
println!(" NumElements: {}", arr.num_elements);
println!(" MaxElements: {}", arr.max_elements);
}
Err(e) => {
eprintln!("GUObjectArray not found: {}", e);
}
}
}
Err(e) => {
eprintln!(
"GNames not found (required for GUObjectArray): {}",
e
);
}
}
}
"classuclass" => {
// Find Class UClass via self-referential pattern
println!("Searching for Class UClass (self-referential)...");
match memory::discover_class_uclass(source) {
Ok(addr) => {
println!("Class UClass found at: {:#x}", addr);
// Read and dump the UObject structure
println!("\nUObject structure dump:");
for offset in (0..0x40usize).step_by(8) {
if let Ok(val) = source.read_u64(addr + offset) {
println!(" +{:#04x}: {:#018x}", offset, val);
}
}
}
Err(e) => {
eprintln!("Class UClass not found: {}", e);
}
}
}
_ => {
eprintln!("Unknown target: {}. Use 'gnames', 'guobjectarray', 'classuclass', or 'all'", target);
}
}
}
MemoryAction::Objects { class, limit } => {
let source = mem_source!();
// First discover GNames
let gnames =
memory::discover_gnames(source).context("Failed to find GNames pool")?;
println!("GNames at: {:#x}", gnames.address);
// For now, we can only search for class names in the FName pool
// Full object enumeration requires GUObjectArray
if let Some(class_name) = class {
println!("Searching for '{}' in FName pool...", class_name);
// Search for the class name in memory
let pattern = class_name.as_bytes();
let results =
memory::scan_pattern(source, pattern, &vec![1u8; pattern.len()])?;
println!(
"Found {} occurrences of '{}':",
results.len().min(limit),
class_name
);
for (i, addr) in results.iter().take(limit).enumerate() {
println!(" {}: {:#x}", i + 1, addr);
// Try to read context around the match
if let Ok(context) = source.read_bytes(addr.saturating_sub(16), 64) {
// Show as hex + ascii
print!(" ");
for byte in &context[..32.min(context.len())] {
print!("{:02x} ", byte);
}
println!();
print!(" ");
for byte in &context[..32.min(context.len())] {
let c = *byte as char;
if c.is_ascii_graphic() || c == ' ' {
print!("{}", c);
} else {
print!(".");
}
}
println!();
}
}
if results.len() > limit {
println!("... and {} more", results.len() - limit);
}
} else {
println!("No class filter specified. Showing FName pool sample:");
for (idx, name) in &gnames.sample_names {
println!(" [{}] {}", idx, name);
}
println!("\nUse --class <name> to search for specific classes");
println!("Example: bl4 inject objects --class RarityWeightData");
}
}
MemoryAction::Fname { index, debug } => {
let source = mem_source!();
// Try to discover the full FNamePool structure using known address
match memory::FNamePool::discover(source) {
Ok(pool) => {
println!("FNamePool found at {:#x}", pool.header_addr);
println!(" Blocks: {}", pool.blocks.len());
println!(" Cursor: {}", pool.current_cursor);
let reader = memory::FNameReader::new(pool);
// Always dump raw bytes when --debug is specified
if debug {
reader.debug_read(source, index)?;
}
let mut reader = reader;
match reader.read_name(source, index) {
Ok(name) => {
println!("\nFName[{}] = \"{}\"", index, name);
// Show index breakdown
let block = (index & 0x3FFFFFFF) >> 16;
let offset = ((index & 0xFFFF) * 2) as usize;
println!(" Block: {}, Offset: {:#x}", block, offset);
}
Err(e) => {
eprintln!("Failed to read FName[{}]: {}", index, e);
if !debug {
reader.debug_read(source, index)?;
}
}
}
}
Err(e) => {
// Fall back to pattern-based discovery
eprintln!("FNamePool::discover failed: {}", e);
let gnames = memory::discover_gnames(source)
.context("Failed to find GNames pool")?;
println!("Using legacy FName reader (block 0 only)");
let mut reader = memory::FNameReader::new_legacy(gnames.address);
match reader.read_name(source, index) {
Ok(name) => println!("FName[{}] = \"{}\"", index, name),
Err(e) => eprintln!("Failed to read FName[{}]: {}", index, e),
}
}
}
}
MemoryAction::FnameSearch { query } => {
let source = mem_source!();
// Discover FNamePool to get all blocks
let pool = memory::FNamePool::discover(source)
.context("Failed to discover FNamePool")?;
println!(
"Searching for \"{}\" across {} FName blocks...",
query,
pool.blocks.len()
);
let search_bytes = query.as_bytes();
let mut found = Vec::new();
// Search all blocks
for (block_idx, &block_addr) in pool.blocks.iter().enumerate() {
if block_addr == 0 {
continue;
}
// Read block data (64KB per block)
let block_data = match source.read_bytes(block_addr, 64 * 1024) {
Ok(d) => d,
Err(_) => continue,
};
for (pos, window) in block_data.windows(search_bytes.len()).enumerate() {
if window == search_bytes {
// Found match - try to find the entry start
if pos >= 2 {
let header = &block_data[pos - 2..pos];
let header_val = byteorder::LE::read_u16(header);
let len = (header_val >> 6) as usize;
// Verify this is a valid entry header
if len > 0 && len <= 1024 {
// Read the full name from header position
let name_start = pos - 2 + 2;
let name_end = name_start + len;
if name_end <= block_data.len() {
let full_name = String::from_utf8_lossy(
&block_data[name_start..name_end],
);
let byte_offset = pos - 2;
// FName index = (block_idx << 16) | (byte_offset / 2)
let fname_index = ((block_idx as u32) << 16)
| ((byte_offset / 2) as u32);
found.push((
fname_index,
block_idx,
byte_offset,
full_name.to_string(),
));
}
}
}
}
}
}
if found.is_empty() {
println!("No matches found for \"{}\"", query);
} else {
println!("Found {} matches:", found.len());
for (fname_index, block_idx, byte_offset, name) in found.iter().take(50) {
println!(
" FName[{:#x}] = \"{}\" (block {}, offset {:#x})",
fname_index, name, block_idx, byte_offset
);
}
if found.len() > 50 {
println!(" ... and {} more", found.len() - 50);
}
}
}
MemoryAction::FindClassUClass => {
let source = mem_source!();
// First discover FNamePool to resolve names
let _gnames =
memory::discover_gnames(source).context("Failed to find GNames pool")?;
let pool = memory::FNamePool::discover(source)
.context("Failed to discover FNamePool")?;
let mut fname_reader = memory::FNameReader::new(pool);
// Get code bounds for vtable validation
let code_bounds = memory::find_code_bounds(source)?;
println!("Searching for Class UClass...");
println!(" Code bounds: {} ranges", code_bounds.ranges.len());
// Try multiple offset combinations for ClassPrivate and NamePrivate
// Standard UE5: ClassPrivate=0x10, NamePrivate=0x18
// BL4 discovered: ClassPrivate=0x18, NamePrivate=0x30
let offset_combos: &[(usize, usize, &str)] = &[
(0x18, 0x30, "BL4 (0x18/0x30)"),
(0x10, 0x18, "Standard UE5"),
(0x10, 0x30, "Mixed A"),
(0x20, 0x38, "Offset +8"),
];
for &(class_off, name_off, desc) in offset_combos {
println!(
"\nTrying {} - ClassPrivate={:#x}, NamePrivate={:#x}...",
desc, class_off, name_off
);
let mut found_self_refs: Vec<(usize, usize, u32, String)> = Vec::new();
let mut found_class = false;
let header_size = name_off + 8;
for region in source.regions() {
// Only require readable (data sections may be read-only)
if !region.is_readable() {
continue;
}
// Include both PE image range AND heap
// PE: 0x140000000-0x175000000
// Heap: typically starts around 0x1000000+
let in_pe = region.start >= 0x140000000 && region.start <= 0x175000000;
let in_heap = region.start >= 0x1000000 && region.start < 0x140000000;
if !in_pe && !in_heap {
continue;
}
// Skip very large regions
if region.size() > 100 * 1024 * 1024 {
continue;
}
let data = match source.read_bytes(region.start, region.size()) {
Ok(d) => d,
Err(_) => continue,
};
// Scan for potential UObjects (8-byte aligned)
for offset in (0..data.len().saturating_sub(header_size)).step_by(8) {
let obj_addr = region.start + offset;
// Check vtable pointer - must be in valid data range
let vtable_ptr =
byteorder::LE::read_u64(&data[offset..offset + 8]) as usize;
if !(0x140000000..=0x175000000).contains(&vtable_ptr) {
continue;
}
// Vtable's first entry must point to CODE
let first_func = match source.read_bytes(vtable_ptr, 8) {
Ok(vt) => byteorder::LE::read_u64(&vt) as usize,
Err(_) => continue,
};
if !code_bounds.contains(first_func) {
continue;
}
// Check ClassPrivate for self-reference
let class_ptr = byteorder::LE::read_u64(
&data[offset + class_off..offset + class_off + 8],
) as usize;
if class_ptr != obj_addr {
continue;
}
// Self-referential! Read the name
let fname_idx = byteorder::LE::read_u32(
&data[offset + name_off..offset + name_off + 4],
);
let name = fname_reader
.read_name(source, fname_idx)
.unwrap_or_else(|_| format!("<idx:{}>", fname_idx));
found_self_refs.push((
obj_addr,
vtable_ptr,
fname_idx,
name.clone(),
));
if fname_idx == memory::FNAME_CLASS_INDEX || name == "Class" {
println!("\n*** FOUND Class UClass at {:#x} ***", obj_addr);
println!(
" VTable: {:#x}, vtable[0]: {:#x}",
vtable_ptr, first_func
);
println!(" FName index: {} = \"{}\"", fname_idx, name);
found_class = true;
}
}
}
println!(
" Found {} self-referential objects:",
found_self_refs.len()
);
for (addr, vtable, fname_idx, name) in found_self_refs.iter().take(10) {
let marker = if *fname_idx == memory::FNAME_CLASS_INDEX {
" <-- CLASS!"
} else {
""
};
println!(
" {:#x}: vtable={:#x}, fname={} \"{}\"{}",
addr, vtable, fname_idx, name, marker
);
}
if found_class {
println!("\n=== SUCCESS with {} offsets! ===", desc);
break;
}
}
}
MemoryAction::ListUClasses { limit, filter } => {
let source = mem_source!();
// Discover FNamePool to resolve names
let _gnames =
memory::discover_gnames(source).context("Failed to find GNames pool")?;
let pool = memory::FNamePool::discover(source)
.context("Failed to discover FNamePool")?;
let mut fname_reader = memory::FNameReader::new(pool);
// Find all UClass instances
println!(
"Finding all UClass instances (ClassPrivate == {:#x})...\n",
memory::UCLASS_METACLASS_ADDR
);
let classes = memory::find_all_uclasses(source, &mut fname_reader)
.context("Failed to enumerate UClass instances")?;
// Apply filter if provided
let filtered: Vec<_> = if let Some(ref pattern) = filter {
let pattern_lower = pattern.to_lowercase();
classes
.iter()
.filter(|c| c.name.to_lowercase().contains(&pattern_lower))
.collect()
} else {
classes.iter().collect()
};
println!(
"Found {} UClass instances{}\n",
filtered.len(),
filter
.as_ref()
.map(|f| format!(" matching '{}'", f))
.unwrap_or_default()
);
// Show results
let show_count = if limit == 0 {
filtered.len()
} else {
limit.min(filtered.len())
};
for class in filtered.iter().take(show_count) {
println!(
" {:#x}: {} (FName {})",
class.address, class.name, class.name_index
);
}
if show_count < filtered.len() {
println!(
"\n ... and {} more (use --limit 0 to show all)",
filtered.len() - show_count
);
}
// Show some stats
let game_classes: Vec<_> = filtered
.iter()
.filter(|c| {
c.name.starts_with("U")
|| c.name.starts_with("A")
|| c.name.contains("_")
})
.collect();
let core_classes: Vec<_> = filtered
.iter()
.filter(|c| {
!c.name.starts_with("U")
&& !c.name.starts_with("A")
&& !c.name.contains("_")
})
.collect();
println!("\nClass categories:");
println!(" Game classes (U*/A*/*_*): {}", game_classes.len());
println!(" Core/Native classes: {}", core_classes.len());
}
MemoryAction::ListObjects {
limit,
class_filter,
name_filter,
stats,
} => {
let source = mem_source!();
// Discover GNames first (needed for FName resolution)
eprintln!("Searching for GNames pool...");
let gnames =
memory::discover_gnames(source).context("Failed to discover GNames")?;
eprintln!("GNames found at: {:#x}\n", gnames.address);
// Discover GUObjectArray via pattern-based search
eprintln!("Searching for GUObjectArray...");
let guobj = memory::discover_guobject_array(source, gnames.address)
.context("Failed to discover GUObjectArray")?;
// Discover FNamePool for name reading
let pool = memory::FNamePool::discover(source)
.context("Failed to discover FNamePool")?;
let mut fname_reader = memory::FNameReader::new(pool);
println!("Enumerating UObjects from GUObjectArray...");
println!(" Total objects: {}", guobj.num_elements);
println!(" Item size: {} bytes\n", guobj.item_size);
// Statistics tracking
let mut total_valid = 0usize;
let mut class_counts: std::collections::HashMap<String, usize> =
std::collections::HashMap::new();
let mut shown = 0usize;
let class_filter_lower = class_filter.as_ref().map(|s| s.to_lowercase());
let name_filter_lower = name_filter.as_ref().map(|s| s.to_lowercase());
// Iterate over all objects
for (idx, obj_ptr) in guobj.iter_objects(source) {
// Read UObject header
let obj_data = match source.read_bytes(obj_ptr, memory::UOBJECT_HEADER_SIZE)
{
Ok(d) => d,
Err(_) => continue,
};
let class_ptr = byteorder::LE::read_u64(
&obj_data
[memory::UOBJECT_CLASS_OFFSET..memory::UOBJECT_CLASS_OFFSET + 8],
) as usize;
let name_idx = byteorder::LE::read_u32(
&obj_data[memory::UOBJECT_NAME_OFFSET..memory::UOBJECT_NAME_OFFSET + 4],
);
// Read object name
let obj_name = fname_reader
.read_name(source, name_idx)
.unwrap_or_else(|_| format!("FName_{}", name_idx));
// Read class name (need to read the class object's name)
let class_name = if class_ptr != 0 {
if let Ok(class_data) =
source.read_bytes(class_ptr, memory::UOBJECT_HEADER_SIZE)
{
let class_name_idx = byteorder::LE::read_u32(
&class_data[memory::UOBJECT_NAME_OFFSET
..memory::UOBJECT_NAME_OFFSET + 4],
);
fname_reader
.read_name(source, class_name_idx)
.unwrap_or_else(|_| format!("FName_{}", class_name_idx))
} else {
"Unknown".to_string()
}
} else {
"Null".to_string()
};
total_valid += 1;
*class_counts.entry(class_name.clone()).or_insert(0) += 1;
// Apply filters
let class_match = class_filter_lower
.as_ref()
.map(|f| class_name.to_lowercase().contains(f))
.unwrap_or(true);
let name_match = name_filter_lower
.as_ref()
.map(|f| obj_name.to_lowercase().contains(f))
.unwrap_or(true);
if class_match && name_match && !stats && shown < limit {
println!("[{}] {:#x}: {} ({})", idx, obj_ptr, obj_name, class_name);
shown += 1;
}
// Progress indicator
if total_valid.is_multiple_of(50000) {
eprint!("\r Scanned {} objects...", total_valid);
}
}
eprintln!("\r Scanned {} valid objects total.", total_valid);
if stats || class_filter.is_some() || name_filter.is_some() {
println!("\nStatistics:");
println!(" Total valid objects: {}", total_valid);
println!(" Unique classes: {}", class_counts.len());
// Sort classes by count and show top 20
let mut sorted_classes: Vec<_> = class_counts.into_iter().collect();
sorted_classes.sort_by(|a, b| b.1.cmp(&a.1));
println!("\nTop 20 classes by instance count:");
for (class_name, count) in sorted_classes.iter().take(20) {
println!(" {:6} {}", count, class_name);
}
}
if !stats && shown >= limit && limit > 0 {
println!(
"\n... showing first {} matches (use --limit N to see more)",
limit
);
}
}
MemoryAction::AnalyzeDump => {
let source = mem_source!();
// Run comprehensive dump analysis
memory::analyze_dump(source).context("Dump analysis failed")?;
}
MemoryAction::DumpUsmap { output } => {
let source = mem_source!();
// Step 1: Find GNames pool
println!("Step 1: Finding GNames pool...");
let gnames =
memory::discover_gnames(source).context("Failed to find GNames pool")?;
println!(" GNames at: {:#x}", gnames.address);
// Step 2: Find GUObjectArray
println!("\nStep 2: Finding GUObjectArray...");
let guobj_array = memory::discover_guobject_array(source, gnames.address)
.context("Failed to find GUObjectArray")?;
println!(" GUObjectArray at: {:#x}", guobj_array.address);
println!(" Objects ptr: {:#x}", guobj_array.objects_ptr);
println!(" NumElements: {}", guobj_array.num_elements);
// Step 3: Walk GUObjectArray to find reflection objects
println!("\nStep 3: Walking GUObjectArray to find reflection objects...");
let pool = memory::FNamePool::discover(source)
.context("Failed to discover FNamePool")?;
let mut fname_reader = memory::FNameReader::new(pool);
let reflection_objects =
memory::walk_guobject_array(source, &guobj_array, &mut fname_reader)
.context("Failed to walk GUObjectArray")?;
// Print summary
let class_count = reflection_objects
.iter()
.filter(|o| o.class_name == "Class")
.count();
let struct_count = reflection_objects
.iter()
.filter(|o| o.class_name == "ScriptStruct")
.count();
let enum_count = reflection_objects
.iter()
.filter(|o| o.class_name == "Enum")
.count();
println!("\nFound {} reflection objects:", reflection_objects.len());
println!(" {} UClass", class_count);
println!(" {} UScriptStruct", struct_count);
println!(" {} UEnum", enum_count);
// Print some samples
println!("\nSample classes:");
for obj in reflection_objects
.iter()
.filter(|o| o.class_name == "Class")
.take(10)
{
println!(" {}: {} at {:#x}", obj.class_name, obj.name, obj.address);
}
println!("\nSample structs:");
for obj in reflection_objects
.iter()
.filter(|o| o.class_name == "ScriptStruct")
.take(10)
{
println!(" {}: {} at {:#x}", obj.class_name, obj.name, obj.address);
}
println!("\nSample enums:");
for obj in reflection_objects
.iter()
.filter(|o| o.class_name == "Enum")
.take(10)
{
println!(" {}: {} at {:#x}", obj.class_name, obj.name, obj.address);
}
// Step 4: Extract properties from each struct/class
println!("\nStep 4: Extracting properties...");
let (structs, enums) = memory::extract_reflection_data(
source,
&reflection_objects,
&mut fname_reader,
)
.context("Failed to extract reflection data")?;
// Print some sample properties
println!("\nSample struct properties:");
for s in structs.iter().filter(|s| !s.properties.is_empty()).take(5) {
println!(
" {} ({}): {} props, super={:?}",
s.name,
if s.is_class { "class" } else { "struct" },
s.properties.len(),
s.super_name
);
for prop in s.properties.iter().take(3) {
println!(
" +{:#x} {} : {} ({:?})",
prop.offset,
prop.name,
prop.type_name,
prop.struct_type.as_ref().or(prop.enum_type.as_ref())
);
}
if s.properties.len() > 3 {
println!(" ... and {} more", s.properties.len() - 3);
}
}
println!("\nSample enum values:");
for e in enums.iter().filter(|e| !e.values.is_empty()).take(5) {
println!(" {}: {} values", e.name, e.values.len());
for (name, val) in e.values.iter().take(3) {
println!(" {} = {}", name, val);
}
if e.values.len() > 3 {
println!(" ... and {} more", e.values.len() - 3);
}
}
// Step 5: Write usmap format
memory::write_usmap(&output, &structs, &enums)?;
println!("\nWrote usmap file: {}", output.display());
}
MemoryAction::ListInventory => {
// TODO: Find player controller, walk inventory array
bail!(
"Inventory listing not yet implemented. \
Need to locate player inventory structures first."
);
}
MemoryAction::Read { address, size } => {
let source = mem_source!();
// Parse hex address
let addr = if address.starts_with("0x") || address.starts_with("0X") {
usize::from_str_radix(&address[2..], 16).context("Invalid hex address")?
} else {
address.parse::<usize>().context("Invalid address")?
};
let data = source.read_bytes(addr, size)?;
// Print hex dump
println!("Reading {} bytes at {:#x}:", size, addr);
for (i, chunk) in data.chunks(16).enumerate() {
print!("{:08x} ", addr + i * 16);
for (j, byte) in chunk.iter().enumerate() {
print!("{:02x} ", byte);
if j == 7 {
print!(" ");
}
}
// Pad if last line is short
if chunk.len() < 16 {
for j in chunk.len()..16 {
print!(" ");
if j == 7 {
print!(" ");
}
}
}
print!(" |");
for byte in chunk {
let c = *byte as char;
if c.is_ascii_graphic() || c == ' ' {
print!("{}", c);
} else {
print!(".");
}
}
println!("|");
}
}
MemoryAction::Write { address, bytes } => {
// Writing requires a live process
let proc = process
.as_ref()
.context("Write requires a live process (not available in dump mode)")?;
// Parse hex address
let addr = if address.starts_with("0x") || address.starts_with("0X") {
usize::from_str_radix(&address[2..], 16).context("Invalid hex address")?
} else {
address.parse::<usize>().context("Invalid address")?
};
// Parse hex bytes
let parts: Vec<&str> = bytes.split_whitespace().collect();
let mut data = Vec::new();
for part in parts {
let byte = u8::from_str_radix(part, 16)
.with_context(|| format!("Invalid hex byte: {}", part))?;
data.push(byte);
}
// Show what we're about to write
println!("Writing {} bytes to {:#x}:", data.len(), addr);
print!(" ");
for byte in &data {
print!("{:02x} ", byte);
}
println!();
// Read original bytes first for safety
let original = proc.read_bytes(addr, data.len())?;
print!("Original: ");
for byte in &original {
print!("{:02x} ", byte);
}
println!();
// Write the new bytes
proc.write_bytes(addr, &data)?;
println!("Write successful!");
}
MemoryAction::Scan { pattern } => {
let source = mem_source!();
// Parse pattern like "48 8B 05 ?? ?? ?? ??"
let parts: Vec<&str> = pattern.split_whitespace().collect();
let mut bytes = Vec::new();
let mut mask = Vec::new();
for part in parts {
if part == "??" || part == "?" {
bytes.push(0u8);
mask.push(0u8); // 0 = wildcard
} else {
let byte = u8::from_str_radix(part, 16)
.with_context(|| format!("Invalid hex byte: {}", part))?;
bytes.push(byte);
mask.push(1u8); // 1 = must match
}
}
println!("Scanning for pattern: {}", pattern);
println!("This may take a while...");
let results = memory::scan_pattern(source, &bytes, &mask)?;
if results.is_empty() {
println!("No matches found.");
} else {
println!("Found {} matches:", results.len());
for (i, addr) in results.iter().take(20).enumerate() {
println!(" {}: {:#x}", i + 1, addr);
}
if results.len() > 20 {
println!(" ... and {} more", results.len() - 20);
}
}
}
MemoryAction::Patch {
address,
nop,
bytes,
} => {
// Patching requires a live process
let proc = process
.as_ref()
.context("Patch requires a live process (not available in dump mode)")?;
// Parse hex address
let addr = if address.starts_with("0x") || address.starts_with("0X") {
usize::from_str_radix(&address[2..], 16).context("Invalid hex address")?
} else {
address.parse::<usize>().context("Invalid address")?
};
let patch_bytes = if let Some(nop_count) = nop {
// Generate NOP bytes (0x90 on x86-64)
vec![0x90u8; nop_count]
} else if let Some(hex_bytes) = bytes {
// Parse custom bytes
let parts: Vec<&str> = hex_bytes.split_whitespace().collect();
let mut data = Vec::new();
for part in parts {
let byte = u8::from_str_radix(part, 16)
.with_context(|| format!("Invalid hex byte: {}", part))?;
data.push(byte);
}
data
} else {
bail!("Must specify either --nop <count> or --bytes <hex>");
};
// Read original bytes first
let original = proc.read_bytes(addr, patch_bytes.len())?;
println!("Patching {} bytes at {:#x}", patch_bytes.len(), addr);
print!("Original: ");
for byte in &original {
print!("{:02x} ", byte);
}
println!();
print!("New: ");
for byte in &patch_bytes {
print!("{:02x} ", byte);
}
println!();
// Apply the patch
proc.write_bytes(addr, &patch_bytes)?;
println!("Patch applied!");
}
MemoryAction::Apply { templates } => {
println!("Applying {} template(s)...", templates.len());
println!();
for template in &templates {
// Parse template format: "key=value"
let parts: Vec<&str> = template.splitn(2, '=').collect();
if parts.len() != 2 {
eprintln!("Invalid template format: {} (expected key=value)", template);
continue;
}
let key = parts[0].to_lowercase();
let value = parts[1].to_lowercase();
match key.as_str() {
"droprate" => {
println!("Template: dropRate={}", value);
println!(" Status: Not yet implemented");
println!(" Requires: Finding RarityWeightData instances");
println!(" Known addresses:");
println!(" - RarityWeightData FName: 0x5f9548e");
println!(" - BaseWeight FName: 0x6f3a44c4");
println!(" - GrowthExponent FName: 0x6f3a44b4");
}
"droprarity" => {
println!("Template: dropRarity={}", value);
match value.as_str() {
"legendary" => {
println!(" Target: Force comp_05_legendary");
println!(" Status: Not yet implemented");
println!(" Requires: Patching ItemPool selection code");
}
"epic" => {
println!(" Target: Force comp_04_epic");
println!(" Status: Not yet implemented");
}
"rare" => {
println!(" Target: Force comp_03_rare");
println!(" Status: Not yet implemented");
}
_ => {
eprintln!(" Unknown rarity: {}", value);
eprintln!(
" Valid: legendary, epic, rare, uncommon, common"
);
}
}
}
"luck" => {
println!("Template: luck={}", value);
println!(" Status: Not yet implemented");
println!(" Requires: Finding LuckGlobals instance");
println!(" Known addresses:");
println!(" - LuckGlobals FName: 0x5f95658");
println!(" - LuckCategories FName: 0x6f3a4560");
}
_ => {
eprintln!("Unknown template: {}", key);
eprintln!("Run 'bl4 inject templates' to see available templates");
}
}
println!();
}
println!("Note: Template implementation is work-in-progress.");
println!("See docs/loot.md for current research findings.");
}
MemoryAction::Monitor {
log_file,
filter,
game_only,
} => {
use std::io::BufRead;
println!("Monitoring: {}", log_file.display());
if let Some(ref f) = filter {
println!("Filter: {}", f);
}
if game_only {
println!("Showing only game code addresses (0x140000000+)");
}
println!("Press Ctrl+C to stop\n");
// Tail the log file
let file = std::fs::File::open(&log_file)
.with_context(|| format!("Failed to open {}", log_file.display()))?;
let mut reader = std::io::BufReader::new(file);
// Seek to end first
reader.seek_relative(
std::fs::metadata(&log_file)
.map(|m| m.len() as i64)
.unwrap_or(0),
)?;
loop {
let mut line = String::new();
match reader.read_line(&mut line) {
Ok(0) => {
// No new data, wait a bit
std::thread::sleep(std::time::Duration::from_millis(100));
}
Ok(_) => {
let line = line.trim();
// Apply filter
if let Some(ref f) = filter {
if !line.contains(f) {
continue;
}
}
// Apply game_only filter (addresses 0x140000000+)
if game_only {
if let Some(caller_pos) = line.find("caller=0x") {
let addr_str = &line[caller_pos + 9..];
if let Some(end) =
addr_str.find(|c: char| !c.is_ascii_hexdigit())
{
if let Ok(addr) =
usize::from_str_radix(&addr_str[..end], 16)
{
// Skip addresses below game base
if addr < 0x140000000 {
continue;
}
}
}
}
}
println!("{}", line);
}
Err(e) => {
eprintln!("Read error: {}", e);
break;
}
}
}
}
MemoryAction::ScanString {
query,
before,
after,
limit,
} => {
let source = mem_source!();
println!("Searching for \"{}\" in memory...", query);
let search_bytes = query.as_bytes();
let mask = vec![1u8; search_bytes.len()];
// Use scan_pattern to find all matches
let results = memory::scan_pattern(source, search_bytes, &mask)?;
if results.is_empty() {
println!("No matches found.");
} else {
let show_count = results.len().min(limit);
println!("Found {} matches, showing {}:", results.len(), show_count);
for (i, &addr) in results.iter().take(limit).enumerate() {
println!("\n=== Match {} at {:#x} ===", i + 1, addr);
// Read context around the match
let ctx_start = addr.saturating_sub(before);
let ctx_size = before + search_bytes.len() + after;
if let Ok(data) = source.read_bytes(ctx_start, ctx_size) {
// Print hex dump with context
for j in (0..data.len()).step_by(16) {
let line_addr = ctx_start + j;
let line_end = (j + 16).min(data.len());
let line_bytes = &data[j..line_end];
// Hex bytes
let hex: String = line_bytes
.iter()
.map(|b| format!("{:02x}", b))
.collect::<Vec<_>>()
.join(" ");
// ASCII representation
let ascii: String = line_bytes
.iter()
.map(|&b| {
if (32..127).contains(&b) {
b as char
} else {
'.'
}
})
.collect();
// Mark if this line contains the match
let marker =
if ctx_start + j <= addr && addr < ctx_start + j + 16 {
" <--"
} else {
""
};
println!(
"{:#010x}: {:<48} {}{}",
line_addr, hex, ascii, marker
);
}
}
}
if results.len() > limit {
println!("\n... and {} more matches", results.len() - limit);
}
}
}
MemoryAction::DumpParts { output } => {
let source = mem_source!();
println!("Extracting part definitions from memory dump...");
// Pattern: .part_ - we'll search for this and extract surrounding context
let pattern = b".part_";
let mask = vec![1u8; pattern.len()];
let results = memory::scan_pattern(source, pattern, &mask)?;
println!(
"Found {} occurrences of '.part_', analyzing...",
results.len()
);
let mut parts: std::collections::BTreeMap<String, Vec<String>> =
std::collections::BTreeMap::new();
for &addr in &results {
// Read 64 bytes before and 64 after the match
let ctx_start = addr.saturating_sub(32);
if let Ok(data) = source.read_bytes(ctx_start, 128) {
// Find the .part_ position in our buffer
let rel_offset = addr - ctx_start;
// Look backwards from .part_ for the prefix (XXX_YY)
let mut start = rel_offset;
while start > 0 {
let c = data[start - 1];
if c.is_ascii_alphanumeric() || c == b'_' {
start -= 1;
} else {
break;
}
}
// Look forward for the rest of the part name
let mut end = rel_offset + pattern.len();
while end < data.len() {
let c = data[end];
if c.is_ascii_alphanumeric() || c == b'_' {
end += 1;
} else {
break;
}
}
// Extract the full part name
if let Ok(name) = std::str::from_utf8(&data[start..end]) {
// Validate format: XXX_YY.part_*
if name.contains('.') && name.len() > 10 {
let prefix = name.split('.').next().unwrap_or("");
if prefix.len() >= 5 && prefix.contains('_') {
parts
.entry(prefix.to_string())
.or_default()
.push(name.to_string());
}
}
}
}
}
// Deduplicate and sort
for names in parts.values_mut() {
names.sort();
names.dedup();
}
// Write JSON using manual formatting (no serde_json dependency needed)
let mut json = String::from("{\n");
let mut first_type = true;
for (prefix, names) in &parts {
if !first_type {
json.push_str(",\n");
}
first_type = false;
json.push_str(&format!(" \"{}\": [\n", prefix));
for (i, name) in names.iter().enumerate() {
json.push_str(&format!(" \"{}\"", name));
if i < names.len() - 1 {
json.push(',');
}
json.push('\n');
}
json.push_str(" ]");
}
json.push_str("\n}\n");
std::fs::write(&output, &json)?;
let total_unique: usize = parts.values().map(|v| v.len()).sum();
println!(
"Found {} unique part names across {} weapon types",
total_unique,
parts.len()
);
println!("Written to: {}", output.display());
}
}
}
Commands::Launch { yes } => {
// Find the preload library
let exe_dir = std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|p| p.to_path_buf()));
let lib_path = exe_dir
.as_ref()
.map(|d| d.join("libbl4_preload.so"))
.filter(|p| p.exists())
.or_else(|| {
// Try relative to current dir
let p = PathBuf::from("target/release/libbl4_preload.so");
if p.exists() {
Some(std::fs::canonicalize(p).unwrap_or_default())
} else {
None
}
});
let lib_path = match lib_path {
Some(p) => p,
None => {
bail!(
"Preload library not found. Build it first:\n \
cargo build --release -p bl4-preload"
);
}
};
// Build the launch options string
let launch_options = format!("LD_PRELOAD={} %command%", lib_path.display());
println!("Add to Steam launch options:\n");
println!(" {}\n", launch_options);
println!(
"Options: BL4_RNG_BIAS=max|high|low|min BL4_PRELOAD_ALL=1 BL4_PRELOAD_STACKS=1"
);
println!("Log: /tmp/bl4_preload.log\n");
// Prompt for confirmation
if !yes {
print!("Launch game? [y/N] ");
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
if !input.trim().eq_ignore_ascii_case("y") {
return Ok(());
}
}
Command::new("steam")
.arg("steam://rungameid/1285190")
.status()
.context("Failed to launch Steam")?;
}
Commands::UsmapInfo { path } => {
use byteorder::{LittleEndian as LE, ReadBytesExt};
use std::io::{BufReader, Seek, SeekFrom};
let file = fs::File::open(&path)
.with_context(|| format!("Failed to open {}", path.display()))?;
let mut reader = BufReader::new(file);
// Read header
let magic = reader.read_u16::<LE>()?;
if magic != 0x30C4 {
bail!("Invalid usmap magic: expected 0x30C4, got {:#x}", magic);
}
let version = reader.read_u8()?;
let has_version_info = if version >= 1 {
reader.read_u8()? != 0
} else {
false
};
let compression = reader.read_u32::<LE>()?;
let compressed_size = reader.read_u32::<LE>()?;
let decompressed_size = reader.read_u32::<LE>()?;
println!("=== {} ===", path.display());
println!("Magic: {:#x}", magic);
println!("Version: {}", version);
println!("HasVersionInfo: {}", has_version_info);
println!(
"Compression: {} ({})",
compression,
match compression {
0 => "None",
1 => "Oodle",
2 => "Brotli",
3 => "ZStandard",
_ => "Unknown",
}
);
println!("CompressedSize: {} bytes", compressed_size);
println!("DecompressedSize: {} bytes", decompressed_size);
if compression != 0 {
println!("\n(Compressed payloads not yet supported for detailed analysis)");
} else {
// Read payload
let name_count = reader.read_u32::<LE>()?;
println!("\nNames: {}", name_count);
// Skip names
for _ in 0..name_count {
let len = reader.read_u16::<LE>()? as usize;
reader.seek(SeekFrom::Current(len as i64))?;
}
let enum_count = reader.read_u32::<LE>()?;
println!("Enums: {}", enum_count);
// Count enum values
let mut total_enum_values = 0u64;
for _ in 0..enum_count {
let _name_idx = reader.read_u32::<LE>()?;
let entry_count = reader.read_u16::<LE>()? as u64;
total_enum_values += entry_count;
// Version >= 4 uses ExplicitEnumValues (value u64 + name_idx u32 = 12 bytes)
// Version 3 uses just name indices (4 bytes each)
let bytes_per_entry = if version >= 4 { 12 } else { 4 };
reader.seek(SeekFrom::Current((entry_count * bytes_per_entry) as i64))?;
}
println!("Enum values: {}", total_enum_values);
let struct_count = reader.read_u32::<LE>()?;
println!("Structs: {}", struct_count);
// Count properties
let mut total_props = 0u64;
for _ in 0..struct_count {
let _name_idx = reader.read_u32::<LE>()?;
let _super_idx = reader.read_u32::<LE>()?;
let _prop_count = reader.read_u16::<LE>()?;
let serializable_count = reader.read_u16::<LE>()? as u64;
total_props += serializable_count;
// Skip properties (need to parse each one due to variable size)
for _ in 0..serializable_count {
let _index = reader.read_u16::<LE>()?;
let _array_dim = reader.read_u8()?;
let _name_idx = reader.read_u32::<LE>()?;
// Read property type recursively
fn skip_property_type<R: std::io::Read>(r: &mut R) -> Result<()> {
let type_id = r.read_u8()?;
match type_id {
26 => {
// EnumProperty
skip_property_type(r)?; // inner
r.read_u32::<LE>()?; // enum name
}
9 => {
// StructProperty
r.read_u32::<LE>()?; // struct name
}
8 | 25 | 28 => {
// Array/Set/Optional
skip_property_type(r)?; // inner
}
24 => {
// MapProperty
skip_property_type(r)?; // key
skip_property_type(r)?; // value
}
_ => {} // Simple types have no extra data
}
Ok(())
}
skip_property_type(&mut reader)?;
}
}
println!("Properties: {}", total_props);
}
let file_size = fs::metadata(&path)?.len();
println!("\nFile size: {} bytes", file_size);
}
Commands::UsmapSearch {
path,
pattern,
verbose,
} => {
use byteorder::{LittleEndian as LE, ReadBytesExt};
use std::io::{BufReader, Read, Seek, SeekFrom};
let file = fs::File::open(&path)
.with_context(|| format!("Failed to open {}", path.display()))?;
let mut reader = BufReader::new(file);
// Read header
let magic = reader.read_u16::<LE>()?;
if magic != 0x30C4 {
bail!("Invalid usmap magic: expected 0x30C4, got {:#x}", magic);
}
let version = reader.read_u8()?;
let _has_version_info = if version >= 1 {
reader.read_u8()? != 0
} else {
false
};
let compression = reader.read_u32::<LE>()?;
let _compressed_size = reader.read_u32::<LE>()?;
let _decompressed_size = reader.read_u32::<LE>()?;
if compression != 0 {
bail!("Compressed usmap files not yet supported for search");
}
// Read names table
let name_count = reader.read_u32::<LE>()?;
let mut names: Vec<String> = Vec::with_capacity(name_count as usize);
for _ in 0..name_count {
let len = reader.read_u16::<LE>()? as usize;
let mut buf = vec![0u8; len];
reader.read_exact(&mut buf)?;
names.push(String::from_utf8_lossy(&buf).into_owned());
}
// Read enums
let enum_count = reader.read_u32::<LE>()?;
let pattern_lower = pattern.to_lowercase();
let mut found_enums = Vec::new();
for _ in 0..enum_count {
let name_idx = reader.read_u32::<LE>()? as usize;
let entry_count = reader.read_u16::<LE>()? as usize;
let name = names.get(name_idx).cloned().unwrap_or_default();
if name.to_lowercase().contains(&pattern_lower) {
let mut entries = Vec::new();
for _ in 0..entry_count {
let entry_idx = reader.read_u32::<LE>()? as usize;
entries.push(names.get(entry_idx).cloned().unwrap_or_default());
}
found_enums.push((name, entries));
} else {
// Skip entries
reader.seek(SeekFrom::Current((entry_count * 4) as i64))?;
}
}
// Read structs
let struct_count = reader.read_u32::<LE>()?;
let mut found_structs = Vec::new();
// Property type names for display
let type_names = [
"Byte",
"Bool",
"Int",
"Float",
"Object",
"Name",
"Delegate",
"Double",
"Array",
"Struct",
"Str",
"Text",
"Interface",
"MulticastDelegate",
"WeakObject",
"LazyObject",
"AssetObject",
"SoftObject",
"UInt64",
"UInt32",
"UInt16",
"Int64",
"Int16",
"Int8",
"Map",
"Set",
"Enum",
"FieldPath",
"Optional",
"Utf8Str",
"AnsiStr",
];
fn read_property_type<R: std::io::Read>(
r: &mut R,
names: &[String],
type_names: &[&str],
) -> Result<String> {
let type_id = r.read_u8()? as usize;
let base_type = type_names.get(type_id).unwrap_or(&"Unknown");
Ok(match type_id {
26 => {
// EnumProperty
let _inner = read_property_type(r, names, type_names)?;
let enum_idx = r.read_u32::<LE>()? as usize;
let enum_name = names.get(enum_idx).cloned().unwrap_or_default();
format!("Enum<{}>", enum_name)
}
9 => {
// StructProperty
let struct_idx = r.read_u32::<LE>()? as usize;
let struct_name = names.get(struct_idx).cloned().unwrap_or_default();
format!("Struct<{}>", struct_name)
}
8 => {
// ArrayProperty
let inner = read_property_type(r, names, type_names)?;
format!("Array<{}>", inner)
}
25 => {
// SetProperty
let inner = read_property_type(r, names, type_names)?;
format!("Set<{}>", inner)
}
28 => {
// OptionalProperty
let inner = read_property_type(r, names, type_names)?;
format!("Optional<{}>", inner)
}
24 => {
// MapProperty
let key = read_property_type(r, names, type_names)?;
let value = read_property_type(r, names, type_names)?;
format!("Map<{}, {}>", key, value)
}
_ => base_type.to_string(),
})
}
for _ in 0..struct_count {
let name_idx = reader.read_u32::<LE>()? as usize;
let super_idx = reader.read_u32::<LE>()? as usize;
let _prop_count = reader.read_u16::<LE>()?;
let serializable_count = reader.read_u16::<LE>()? as usize;
let name = names.get(name_idx).cloned().unwrap_or_default();
let super_name = if super_idx == 0xFFFFFFFF {
None
} else {
names.get(super_idx).cloned()
};
// Read properties
let mut properties = Vec::new();
for _ in 0..serializable_count {
let _index = reader.read_u16::<LE>()?;
let array_dim = reader.read_u8()?;
let prop_name_idx = reader.read_u32::<LE>()? as usize;
let prop_name = names.get(prop_name_idx).cloned().unwrap_or_default();
let prop_type = read_property_type(&mut reader, &names, &type_names)?;
properties.push((prop_name, prop_type, array_dim));
}
if name.to_lowercase().contains(&pattern_lower) {
found_structs.push((name, super_name, properties));
}
}
// Print results
if !found_enums.is_empty() {
println!(
"=== Enums matching '{}' ({}) ===",
pattern,
found_enums.len()
);
for (name, entries) in &found_enums {
println!("\n{} ({} values)", name, entries.len());
if verbose {
for (i, entry) in entries.iter().enumerate() {
println!(" {} = {}", i, entry);
}
}
}
}
if !found_structs.is_empty() {
println!(
"\n=== Structs matching '{}' ({}) ===",
pattern,
found_structs.len()
);
for (name, super_name, properties) in &found_structs {
println!(
"\n{}{} ({} properties)",
name,
super_name
.as_ref()
.map(|s| format!(" : {}", s))
.unwrap_or_default(),
properties.len()
);
if verbose {
for (prop_name, prop_type, array_dim) in properties {
let dim_str = if *array_dim > 1 {
format!("[{}]", array_dim)
} else {
String::new()
};
println!(" {} {}{}", prop_type, prop_name, dim_str);
}
}
}
}
if found_enums.is_empty() && found_structs.is_empty() {
println!("No enums or structs found matching '{}'", pattern);
}
}
Commands::ExtractPartPools { input, output } => {
use std::collections::BTreeMap;
// Read the parts database (memory-extracted names + verified category assignments)
let data = fs::read_to_string(&input)
.with_context(|| format!("Failed to read {}", input.display()))?;
// Parse parts array from JSON
// Structure: { "parts": [ { "category": N, "name": "...", ... }, ... ], "categories": {...} }
let parts_start = data.find("\"parts\"").context("Missing 'parts' key")?;
let array_start = data[parts_start..]
.find('[')
.context("Missing parts array")?
+ parts_start;
// Find the matching closing bracket
let mut depth = 0;
let mut array_end = array_start;
for (i, c) in data[array_start..].char_indices() {
match c {
'[' => depth += 1,
']' => {
depth -= 1;
if depth == 0 {
array_end = array_start + i;
break;
}
}
_ => {}
}
}
let parts_json = &data[array_start..=array_end];
// Parse part entries - only need category and name
struct PartEntry {
category: i64,
name: String,
}
let mut parts: Vec<PartEntry> = Vec::new();
let mut in_object = false;
let mut current_category: i64 = -1;
let mut current_name = String::new();
let mut depth = 0;
for (i, c) in parts_json.char_indices() {
match c {
'{' => {
depth += 1;
if depth == 1 {
in_object = true;
current_category = -1;
current_name.clear();
}
}
'}' => {
depth -= 1;
if depth == 0 && in_object {
if current_category > 0 && !current_name.is_empty() {
parts.push(PartEntry {
category: current_category,
name: std::mem::take(&mut current_name),
});
}
in_object = false;
}
}
'"' if in_object && depth == 1 => {
let rest = &parts_json[i + 1..];
if let Some(end) = rest.find('"') {
let key = &rest[..end];
let after_key = &rest[end + 1..];
if let Some(colon) = after_key.find(':') {
let value_start = after_key[colon + 1..].trim_start();
match key {
"category" => {
let num_end = value_start
.find(|c: char| !c.is_ascii_digit() && c != '-')
.unwrap_or(value_start.len());
if let Ok(n) = value_start[..num_end].parse::<i64>() {
current_category = n;
}
}
"name" => {
if let Some(name_rest) = value_start.strip_prefix('"') {
if let Some(name_end) = name_rest.find('"') {
current_name = name_rest[..name_end].to_string();
}
}
}
_ => {}
}
}
}
}
_ => {}
}
}
// Group parts by category
let mut by_category: BTreeMap<i64, Vec<String>> = BTreeMap::new();
for part in parts {
by_category
.entry(part.category)
.or_default()
.push(part.name);
}
// Sort parts within each category alphabetically (consistent ordering)
for parts_vec in by_category.values_mut() {
parts_vec.sort();
}
// Parse category names from the input
let mut category_names: BTreeMap<i64, String> = BTreeMap::new();
if let Some(cats_start) = data.find("\"categories\"") {
if let Some(obj_start) = data[cats_start..].find('{') {
let cats_section = &data[cats_start + obj_start..];
// Simple parsing for "N": {"name": "..."}
let mut pos = 0;
while let Some(quote_pos) = cats_section[pos..].find('"') {
let key_start = pos + quote_pos + 1;
if let Some(key_end) = cats_section[key_start..].find('"') {
let key = &cats_section[key_start..key_start + key_end];
if let Ok(cat_id) = key.parse::<i64>() {
// Look for "name": "..." after this
let after = &cats_section[key_start + key_end..];
if let Some(name_pos) = after.find("\"name\"") {
let name_section = &after[name_pos + 7..];
if let Some(val_start) = name_section.find('"') {
let name_rest = &name_section[val_start + 1..];
if let Some(val_end) = name_rest.find('"') {
category_names
.insert(cat_id, name_rest[..val_end].to_string());
}
}
}
}
pos = key_start + key_end + 1;
} else {
break;
}
}
}
}
// Build output JSON with clear metadata
let mut json = String::from("{\n");
json.push_str(&format!(
" \"version\": \"{}\",\n",
env!("CARGO_PKG_VERSION")
));
json.push_str(" \"source\": \"parts_database.json (memory-extracted part names)\",\n");
json.push_str(" \"notes\": {\n");
json.push_str(" \"part_names\": \"Extracted from game memory via string pattern matching - AUTHORITATIVE\",\n");
json.push_str(" \"category_assignments\": \"Based on name prefix matching, verified by serial decode - VERIFIED\",\n");
json.push_str(" \"part_order\": \"Alphabetical within category - NOT authoritative, use memory extraction for true indices\"\n");
json.push_str(" },\n");
json.push_str(" \"pools\": {\n");
let pool_count = by_category.len();
for (i, (category, cat_parts)) in by_category.iter().enumerate() {
let cat_name = category_names
.get(category)
.cloned()
.unwrap_or_else(|| format!("Category {}", category));
json.push_str(&format!(" \"{}\": {{\n", category));
json.push_str(&format!(
" \"name\": \"{}\",\n",
cat_name.replace('"', "\\\"")
));
json.push_str(&format!(" \"part_count\": {},\n", cat_parts.len()));
json.push_str(" \"parts\": [\n");
for (j, part) in cat_parts.iter().enumerate() {
let escaped = part.replace('\\', "\\\\").replace('"', "\\\"");
json.push_str(&format!(" \"{}\"", escaped));
if j < cat_parts.len() - 1 {
json.push(',');
}
json.push('\n');
}
json.push_str(" ]\n");
json.push_str(" }");
if i < pool_count - 1 {
json.push(',');
}
json.push('\n');
}
json.push_str(" },\n");
// Summary
json.push_str(" \"summary\": {\n");
json.push_str(&format!(" \"total_pools\": {},\n", pool_count));
let total_parts: usize = by_category.values().map(|v| v.len()).sum();
json.push_str(&format!(" \"total_parts\": {}\n", total_parts));
json.push_str(" }\n");
json.push_str("}\n");
fs::write(&output, &json)?;
println!(
"Extracted {} part pools with {} total parts",
pool_count, total_parts
);
println!("\nData sources:");
println!(" Part names: Memory extraction (authoritative)");
println!(" Categories: Prefix matching (verified by decode)");
println!(" Part order: Alphabetical (not authoritative)");
println!("\nWritten to: {}", output.display());
}
}
Ok(())
}