asc-cli 0.1.1

asc-rs command line: getclass / getmanifest / findrefs over an APK without preprocessing.
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
//! `asc` command line entry.

#[cfg(unix)]
mod daemon;
mod harmony;
mod output;
mod settings;

use asc_engine::asc_cache::{DiskCache, DiskCapacity};
use asc_engine::config::Config;
use asc_engine::{CacheConfig, CallQuery, CallRoots, Device, Direction, Engine, FindOptions, HierarchyQuery, Lineage, RefContext, names};
use asc_findrefs::Query;
use asc_mcp::format::{ProgramFormat, left_out_note};
use clap::{Args, Parser, Subcommand, ValueEnum};
use output::{Io, LocalEngines, SpillTarget, Window};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::atomic::AtomicBool;
use std::time::Instant;

/// Global options: the head of both the short (`-h`) and the long (`--help`) top-level help.
macro_rules! help_global_options {
    () => {
        "global options (accepted by every command, after it too):
  --set KEY=VALUE     any setting of `asc config` (repeatable), e.g. --set memory.max=4G
  --threads N         = --set threads=N
  --no-cache          = --set cache.enabled=off
  --cache-dir DIR     = --set cache.dir=DIR
  --cache-max-mb MIB  = --set cache.max=MIB
  --memory-mb MIB     = --set memory.max=MIB (mcp and the daemon; one-shot commands keep none)
  --debug             timing and cache statistics on stderr

"
    };
}

/// Exit status: in both top-level helps.
macro_rules! help_exit_status {
    () => {
        "exit status:
  0  success
  1  error (bad arguments, unreadable APK, class not found, output not writable, ...)
  2  findrefs / callgraph finished, but one or more DEX (or ABC) entries could not be searched (details on stderr)"
    };
}

/// `asc -h`: the common points and a few examples per format.
const HELP_SHORT: &str = concat!(
    help_global_options!(),
    "common:
  Class names: rs.asc.Main or Lrs/asc/Main;. The input is an APK, jar or .dex, or a
  HarmonyOS .hap / .hsp / .app / .abc; a directory or `,` list is read as one program.
  Output is one record per line, columns separated by ` | `; `#` lines are headers and hints.

examples (Android):
  asc manifest-summary app.apk | grep exported=true
  asc findrefs app.apk string 'https?://' --limit 50
  asc findrefs app.apk method 'android.webkit.WebView->loadUrl' --context 3
  asc getclass app.apk rs.asc.Main --method onCreate
  asc callgraph app.apk rs.asc.Main onCreate --depth 3

examples (HarmonyOS):
  asc manifest-summary entry.hap | grep exported=true
  asc getclass entry.hap pages/Index --method Index.build
  asc findrefs entry.hap call 'import:@ohos:net\\.http.*\\.request$'
  asc callgraph entry.hap --to 'call:^import:@ohos:net\\.http' --depth 4

",
    help_exit_status!(),
    "

`asc --help` adds the settings, every example and the Android / HarmonyOS details;
`asc <command> --help` shows one command."
);

/// `asc --help`: everything, the examples grouped by format.
const HELP_LONG: &str = concat!(
    help_global_options!(),
    "settings:
  Threads, memory and disk cache budgets are settings: a flag beats $ASC_<KEY>, which
  beats ~/.config/asc/config.toml ($ASC_CONFIG), which beats the default; the
  automatic defaults follow this machine. `asc config` lists them with their values
  and sources (--json for scripts).

common:
  Class names accept both rs.asc.Main and Lrs/asc/Main;.
  Commands with -o/--output write to stdout when the option is omitted.
  Output is one record per line, columns separated by ` | `; lines starting with `#`
  are headers, totals and hints. --limit / --max-bytes keep stdout short: the whole
  output then goes to a file the last line names, and --offset shows the next records.

Android:
  The APK may also be a jar or a .dex, or several read as one program: a directory (every
  *.apk, *.jar, *.zip, *.dex below it) or paths joined with `,`. DEX names then start with
  their archive (services.jar/classes2.dex); archives without classes*.dex are named in a
  `# warning:` line on stderr (deodex them first).

HarmonyOS:
  A .hap / .hsp, an .app, a bare .abc, or a directory / `,` list of them, is answered by
  listclass, getclass / disassemble, getmanifest, manifest-summary, resources, xml, callgraph,
  hierarchy and findrefs string / prop / global / import / method / number / call / all. A
  class is then a record (pages/Index or its full name), --method a function (Index.build or
  its raw name); the manifest is module.json, each srcEntry joined to its record; an
  encrypted (app-store) .abc is named on stderr: supply the decrypted file.

examples (Android):
  asc getclass app.apk 'Lrs/asc/Main;' -o Main.smali
  asc getclass app.apk rs.asc.Main --threads 16
  asc getclass app.apk rs.asc.Main --dump-dex Main.dex
  asc disassemble app.apk rs.asc.Main --debuginfo
  asc disassemble app.apk rs.asc.Main --method 'run(I)V'
  asc getclass app.apk rs.asc.Main --res-names
  asc listclass app.apk -o classes.txt
  asc listclass app.apk --prefix rs.asc
  asc getmanifest app.apk -o AndroidManifest.xml
  asc getmanifest app.apk --resolve
  asc manifest-summary app.apk | grep exported=true
  asc manifest-summary app.apk --json
  asc resources app.apk string/app_name
  asc resources app.apk 0x7f0d0001 --resolve
  asc resources app.apk --search 'https?://' --in value
  asc resources app.apk -o resources.txt
  asc xml app.apk res/xml/network_security_config.xml
  asc findrefs app.apk string token -o string_refs.txt
  asc findrefs app.apk string 'a.b(c)' --literal
  asc findrefs app.apk type rs.asc.Main
  asc findrefs app.apk extends android.app.Activity -o subclasses.txt
  asc findrefs app.apk impl android.os.IInterface
  asc findrefs app.apk method onCreate --class rs.asc.Main
  asc findrefs app.apk method notify --class MainActivity --fuzzy-class -o method_refs.txt
  asc findrefs app.apk method run --class rs.asc.Main --exact
  asc findrefs app.apk field apiKey -o field_refs.txt
  asc findrefs app.apk field apiKey --access write
  asc findrefs app.apk string token --no-cache
  asc findrefs app.apk string token --context 3
  asc findrefs app.apk method loadUrl --context-method
  asc findrefs app.apk method 'android.provider.Settings$Secure->getString[arg1==\"android_id\"]'
  asc findrefs app.apk method '{literal:device_id}'
  asc findrefs app.apk rules 'method:{string:^https?://} & !type:Lrs/asc/test/'
  asc findrefs app.apk method @methods.txt
  asc findrefs app.apk rules 'override:android.os.IInterface->asBinder'
  asc findrefs app.apk rules 'flag:native & string:AES'
  asc findrefs app.apk rules 'in:{extends:android.app.Service} & annotation:androidx.annotation.RequiresPermission'
  asc callgraph app.apk rs.asc.Main onCreate --depth 3
  asc callgraph app.apk rs.asc.Main 'run(I)V' --callees
  asc findrefs system/framework impl com.android.internal.telephony.ITelephony
  asc callgraph framework.jar,services.jar,TeleService.apk android.telephony.TelephonyManager getImei
  asc callgraph app.apk --to 'method:java.lang.Runtime->exec' --from 'method:Intent.getStringExtra' --depth 5

examples (HarmonyOS):
  asc manifest-summary entry.hap | grep exported=true
  asc manifest-summary entry.hap --file pkgContextInfo.json
  asc manifest-summary entry.hap | grep -E '^(page|route) '
  asc listclass entry.hap --prefix entry/src/main/ets/pages
  asc getclass entry.hap pages/Index --method Index.build
  asc findrefs entry.hap string 'https?://'
  asc findrefs entry.hap prop request --exact --access call
  asc findrefs entry.hap global console --exact
  asc findrefs entry.hap import '@ohos:net\\.http#default'
  asc findrefs entry.hap import '@ohos:' --requests
  asc findrefs entry.hap method Index.build --exact
  asc findrefs entry.hap number 0x9e3779b9
  asc findrefs app-dir number 0x01000003 --entry entry.hap
  asc findrefs entry.hap call 'import:@ohos:net\\.http.*\\.request$'
  asc findrefs entry.hap all 'string:^https?://' 'call:import:@ohos:net\\.http'
  asc callgraph entry.hap entryability/EntryAbility EntryAbility.onCreate --callees --depth 3
  asc callgraph entry.hap '&entry/src/main/ets/pages/Index&->#~@0>#build' --callees --unresolved
  asc callgraph entry.hap --to 'call:^import:@ohos:net\\.http' --depth 4
  asc callgraph entry.hap --to 'call:^import:@ohos:net\\.http' --from 'method:=EntryAbility.onCreate' --depth 8
  asc hierarchy entry.hap 'import:@ohos:app\\.ability\\.UIAbility' --method onCreate
  asc hierarchy entry.hap EntryAbility --supers

examples (resident and cache):
  asc mcp --memory-mb 4096
  asc cache stats
  asc daemon status

",
    help_exit_status!(),
    "

Debug output (--debug) goes to stderr so stdout can be redirected.
On Unix, commands answer through a per-user daemon that keeps programs resident (same output);
ASC_DAEMON=off runs each command in its own process."
);

const EXIT_OK: u8 = 0;
/// `resources --search` rows printed without --limit / --max-bytes.
const RESOURCE_SEARCH_ROWS: usize = 1000;
/// Exit status when `findrefs` skipped at least one DEX entry.
const EXIT_PARTIAL: u8 = 2;
const HARMONY_ONLY_ALL: &str = "--all applies to HarmonyOS programs only (a DEX program has no pseudo records)";
const HARMONY_ONLY_ENTRY: &str = "--entry applies to HarmonyOS programs only";

/// The error of a findrefs kind or option a DEX program does not have.
fn harmony_only(what: &str) -> String {
    format!("{what} applies to HarmonyOS programs only")
}

/// Run a one-shot command against `io` on the engine of its program's
/// format: the exit status. `format` is that of the program as `io` opens it
/// ([`Io::program_path`]). In its own process or in the daemon, a command
/// runs through here.
fn run_program(io: &mut Io<'_>, common: &Common, command: Command, format: ProgramFormat, t_start: Instant) -> Result<u8, String> {
    match format {
        ProgramFormat::Android => run_query(io, common, command, t_start),
        ProgramFormat::Harmony => harmony::run(io, common, command, t_start),
    }
}

#[derive(Parser)]
#[command(name = "asc", about = "Search and disassemble APK and HarmonyOS code without preprocessing.", after_help = HELP_SHORT, after_long_help = HELP_LONG, version, disable_version_flag = true)]
struct Cli {
    /// Print version.
    #[arg(short = 'V', visible_short_alias = 'v', long, action = clap::ArgAction::Version)]
    version: Option<bool>,
    #[command(flatten)]
    common: Common,
    #[command(subcommand)]
    command: Command,
}

#[derive(Args, Clone)]
struct Common {
    /// Enable debug profiling output (written to stderr).
    #[arg(long, global = true, hide = true)]
    debug: bool,
    /// Set any setting of `asc config` (repeatable).
    #[arg(long = "set", global = true, value_name = "KEY=VALUE", hide = true)]
    set: Vec<String>,
    /// Worker thread count (`--set threads=N`).
    #[arg(long, alias = "thread", global = true, value_name = "N", hide = true)]
    threads: Option<usize>,
    /// Do not read or write the on-disk cache (`--set cache.enabled=off`).
    #[arg(long, global = true, hide = true)]
    no_cache: bool,
    /// Cache directory (`--set cache.dir=DIR`).
    #[arg(long, global = true, value_name = "DIR", hide = true)]
    cache_dir: Option<PathBuf>,
    /// On-disk cache budget, in MiB (`--set cache.max=MIB`).
    #[arg(long, global = true, value_name = "MIB", hide = true)]
    cache_max_mb: Option<u64>,
    /// In-memory cache budget of `mcp` and the daemon, in MiB (`--set memory.max=MIB`).
    #[arg(long, global = true, value_name = "MIB", hide = true)]
    memory_mb: Option<u64>,
    /// Show at most N records on stdout (results, rows, classes, smali
    /// lines); the whole output goes to a file named on the last line
    /// (default: $ASC_LIMIT, else no limit).
    #[arg(long, global = true, value_name = "N", help_heading = "Output")]
    limit: Option<usize>,
    /// Show at most N bytes of records on stdout, whole records only, the
    /// rest as with --limit (default: $ASC_MAX_BYTES, else no limit).
    #[arg(long, global = true, value_name = "N", help_heading = "Output")]
    max_bytes: Option<usize>,
    /// Skip the first N records (the next page after a cut output).
    #[arg(long, global = true, value_name = "N", default_value_t = 0, help_heading = "Output")]
    offset: usize,
    /// Disk budget of the directory cut outputs (and `mcp` replies over their
    /// budget) are written to, `out/` in the cache directory; 0 writes none
    /// (`--set cache.spill=MIB`, default 64).
    #[arg(long, global = true, value_name = "MIB", help_heading = "Output")]
    spill_mb: Option<u64>,
    /// The settings these flags, the environment and the config file make
    /// ([`Common::resolve`]).
    #[arg(skip)]
    config: Option<Config>,
}

impl Common {
    /// Read the settings: the flags above, then the environment and the
    /// config file. Every command needs them; `main` calls this first.
    fn resolve(&mut self) -> Result<(), String> {
        let cwd = std::env::current_dir().unwrap_or_default();
        self.resolve_in(&cwd)
    }

    /// [`Common::resolve`] with a relative cache directory given as a flag
    /// (`--cache-dir`, `--set cache.dir=`) taken from `cwd`: the client's,
    /// when the daemon (running in `/`) reads the flags.
    fn resolve_in(&mut self, cwd: &Path) -> Result<(), String> {
        let mut flags: Vec<(String, String)> = Vec::new();
        let mut flag = |key: &str, value: String| flags.push((key.into(), value));
        if let Some(n) = self.threads {
            flag("threads", n.to_string());
        }
        if self.no_cache {
            flag("cache.enabled", "off".into());
        }
        if let Some(d) = &self.cache_dir {
            // Absolute, so a daemon started from here (in `/`) uses the same one.
            flag("cache.dir", cwd.join(d).display().to_string());
        }
        if let Some(mb) = self.cache_max_mb {
            flag("cache.max", mb.to_string());
        }
        if let Some(mb) = self.memory_mb {
            flag("memory.max", mb.to_string());
        }
        if let Some(mb) = self.spill_mb {
            flag("cache.spill", mb.to_string());
        }
        for pair in &self.set {
            let Some((key, value)) = pair.split_once('=') else {
                return Err(format!("--set {pair:?}: expected KEY=VALUE, e.g. --set memory.max=4G (keys: asc config)"));
            };
            let (key, value) = (key.trim(), value.trim());
            match key {
                "cache.dir" if !matches!(value, "" | "default") && !value.starts_with('~') => {
                    flag(key, cwd.join(value).display().to_string());
                }
                _ => flag(key, value.to_string()),
            }
        }
        self.config = Some(Config::load(&flags).map_err(|e| format!("{e} (asc config lists the settings)"))?);
        Ok(())
    }

    fn config(&self) -> &Config {
        self.config.as_ref().expect("Common::resolve runs before any command")
    }

    /// The engine every subcommand uses: shared flags, disk cache unless
    /// disabled, and log lines on stderr so stdout stays clean for redirection.
    fn engine(&self, apk_path: &Path) -> Engine {
        let config = self.config();
        let mut engine = Engine::new(apk_path).with_debug(self.debug).with_threads(config.threads()).with_logger(|m| eprintln!("{m}"));
        if config.cache_enabled.value {
            engine = engine.with_cache(config.one_shot_cache());
        }
        engine
    }

    /// The engine of a HarmonyOS program: opened here, with `--threads` when given.
    fn harmony_engine(&self, path: &Path) -> Result<asc_ark_engine::Engine, asc_ark_engine::EngineError> {
        let engine = asc_ark_engine::Engine::open(path)?;
        Ok(match self.config().fixed_threads() {
            Some(threads) => engine.with_threads(threads),
            None => engine,
        })
    }

    fn disk_cache(&self) -> Option<DiskCache> {
        self.config().disk_cache()
    }

    /// `--offset` / `--limit` / `--max-bytes`, the last two defaulting to
    /// `$ASC_LIMIT` / `$ASC_MAX_BYTES` so an agent host can set them
    /// once.
    fn window(&self) -> Window {
        let env = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse().ok());
        Window {
            offset: self.offset,
            limit: self.limit.or_else(|| env("ASC_LIMIT")),
            max_bytes: self.max_bytes.or_else(|| env("ASC_MAX_BYTES")),
        }
    }

    /// Where a cut output is written: `out/` in the cache directory (else a
    /// per-user runtime directory); `None` with `--spill-mb 0`.
    fn spill(&self) -> Option<SpillTarget> {
        let config = self.config();
        let bytes = config.cache_spill.value.0;
        (bytes > 0).then(|| SpillTarget { dir: asc_mcp::output::SpillDir::default_dir(config.cache_dir().as_deref()), bytes })
    }

    /// Cache of the resident hosts (`mcp`, the daemon): the memory budget
    /// (following this machine unless fixed) plus the disk cache.
    fn resident_cache(&self) -> CacheConfig {
        self.config().resident_cache(&Device::probe())
    }
}

#[derive(Subcommand)]
enum Command {
    /// Locate a class (HarmonyOS: a record) and disassemble it.
    ///
    /// Android: the class is rebuilt into a one-class DEX in memory first.
    Getclass {
        /// Also write the output to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Do not emit .line / .param debug directives.
        #[arg(long)]
        no_debug_info: bool,
        /// Write the rebuilt single-class DEX to this file.
        #[arg(long)]
        dump_dex: Option<PathBuf>,
        /// Render only these methods (no fields): a name (every overload) or a
        /// signature, e.g. run or run(I)V.
        #[arg(long = "method", value_name = "NAME|SIGNATURE")]
        method_signature: Option<String>,
        /// Append `# @type/name` to constants that are resource ids (from resources.arsc).
        /// HarmonyOS: `# type/name "value"` after the instruction that creates
        /// a `$r('app.type.name')` object (from resources.index).
        #[arg(long)]
        res_names: bool,
        /// HarmonyOS: take the record from this ABC entry (ets/modules.abc), when
        /// several define it.
        #[arg(long, value_name = "NAME")]
        entry: Option<String>,
        /// HarmonyOS: write `; line N` where the line of the debug info changes
        /// (with ets/sourceMaps.map in the package: its source line too).
        #[arg(long)]
        lines: bool,
        /// Path to the input APK (or jar, .dex; or a HarmonyOS .hap, .app, .abc); a directory, or paths joined with `,`, read as one program.
        apk_path: PathBuf,
        /// The Dalvik format class name to extract (e.g., Lrs/asc/Main; or rs.asc.Main).
        dalvik_class: String,
    },
    /// Like getclass, without debug directives unless --debuginfo.
    Disassemble {
        /// Write disassembly to this file; default is stdout.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Include DEX .line and .param debug directives.
        #[arg(long)]
        debuginfo: bool,
        /// Render only these methods (no fields): a name (every overload) or a
        /// signature, e.g. run or run(I)V.
        #[arg(long = "method", value_name = "NAME|SIGNATURE")]
        method_signature: Option<String>,
        /// Append `# @type/name` to constants that are resource ids (from resources.arsc).
        /// HarmonyOS: `# type/name "value"` after the instruction that creates
        /// a `$r('app.type.name')` object (from resources.index).
        #[arg(long)]
        res_names: bool,
        /// Write the rebuilt single-class DEX to this file.
        #[arg(long)]
        dump_dex: Option<PathBuf>,
        /// HarmonyOS: take the record from this ABC entry (ets/modules.abc), when
        /// several define it.
        #[arg(long, value_name = "NAME")]
        entry: Option<String>,
        /// HarmonyOS: write `; line N` where the line of the debug info changes
        /// (with ets/sourceMaps.map in the package: its source line too).
        /// `--debuginfo` does the same there.
        #[arg(long)]
        lines: bool,
        /// Path to the input APK (or jar, .dex; or a HarmonyOS .hap, .app, .abc); a directory, or paths joined with `,`, read as one program.
        apk_path: PathBuf,
        /// Class name in dotted or Dalvik form, e.g. rs.asc.Main or Lrs/asc/Main;.
        dalvik_class: String,
    },
    /// List classes (HarmonyOS: records) across all code entries; use --prefix to filter by package/class prefix.
    #[command(visible_alias = "classes")]
    Listclass {
        /// Only list classes with this package/class prefix (e.g., rs.asc or Lrs/asc).
        #[arg(long)]
        prefix: Option<String>,
        /// HarmonyOS: also list the pseudo records (compiler annotations,
        /// system module placeholders). The annotation interfaces of the
        /// program are listed either way, as `kind=annotation`.
        #[arg(long)]
        all: bool,
        /// HarmonyOS: only the records of this ABC entry (ets/widgets.abc)
        /// or package (entry.hap), as the last column names it.
        #[arg(long, value_name = "NAME")]
        entry: Option<String>,
        /// Write class names to this file instead of stdout.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Path to the input APK (or jar, .dex; or a HarmonyOS .hap, .app, .abc); a directory, or paths joined with `,`, read as one program.
        apk_path: PathBuf,
    },
    /// Print the manifest: AndroidManifest.xml decoded to XML (HarmonyOS: module.json).
    ///
    /// Android: AndroidManifest.xml of the APK, decoded to XML.
    ///
    /// HarmonyOS: module.json of each package, re-indented.
    #[command(visible_alias = "manifest")]
    Getmanifest {
        /// Also write the decoded manifest to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Show resource references (@7F0C0001) by name, from resources.arsc.
        #[arg(short, long)]
        resolve: bool,
        /// HarmonyOS: print this document instead of module.json: pack.info
        /// (once for the packages that carry the same bytes) or
        /// pkgContextInfo.json.
        #[arg(long, value_name = "NAME")]
        file: Option<String>,
        /// Path to the input APK (or jar, .dex; or a HarmonyOS .hap, .app); a directory, or paths joined with `,`, read as one program.
        apk_path: PathBuf,
    },
    /// Summarize the manifest's attack surface, one record per line: components
    /// (exported or not, and why), permissions, deep links and more.
    ///
    /// Android: package, application flags, permissions, components (exported or not,
    /// and why), intent filters, deep links, FileProvider paths, network
    /// security config. References are resolved through resources.arsc.
    ///
    /// HarmonyOS: module.json and pack.info of each package: bundle, module,
    /// permissions, each ability / extension (exported or not, and whether
    /// the manifest says so), skills, deep links. The module, ability and
    /// extension lines end with `record=NAME`, the record compiled from
    /// their srcEntry (a name getclass takes), or `record=- (why)`; a
    /// `callbacks` line lists the record's functions named onXxx. A
    /// `$type:name` reference is followed by what it stands for in
    /// resources.index: `label=$string:app_name("Shop")`,
    /// `pages=$profile:main_pages(resources/base/profile/main_pages.json)`.
    /// The page list and the route table the module names are lines too:
    /// `page pages/Index record=NAME`, `route NAME buildFunction=F
    /// source=FILE record=NAME` (grep '^route ', or `| grep -v` them). An
    /// `abc` line names each code entry (as --entry takes it), its status
    /// and the decrypted file it is served from. A pack.info that several
    /// packages carry byte for byte is listed once (`pack-info` lines).
    #[command(alias = "manifest_summary")]
    ManifestSummary {
        /// Print JSON instead of lines.
        #[arg(long)]
        json: bool,
        /// Also write the output to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// HarmonyOS: summarize this document only: module.json, pack.info,
        /// or pkgContextInfo.json (the package table, one line per package
        /// with the number of records it has in the code).
        #[arg(long, value_name = "NAME")]
        file: Option<String>,
        /// Path to the input APK (or jar, .dex; or a HarmonyOS .hap, .app); a directory, or paths joined with `,`, read as one program.
        apk_path: PathBuf,
    },
    /// Query the resource table (resources.arsc; HarmonyOS: resources.index): one line per resource and configuration.
    ///
    /// Android: resources.arsc, one line per resource and configuration,
    /// `0x7f0d0001 string/app_name [zh-rCN] "value"`.
    ///
    /// With no QUERY and no --search, dumps the whole table.
    ///
    /// HarmonyOS: resources.index of each package, rows
    /// `0x01000000 string/app_name [zh_CN] "value"` (`[base]`: the default
    /// value, listed first), starting with `PACKAGE | ` in a program of
    /// several packages. The id is what compiled `$r(...)` objects carry
    /// (`findrefs number ID`); code that looks a resource up by name holds
    /// `app.type.name` as a string (`findrefs string`).
    Resources {
        /// Search names and string values with this regex.
        #[arg(long, value_name = "REGEX", conflicts_with = "query")]
        search: Option<String>,
        /// Match --search as a plain substring.
        #[arg(long, requires = "search")]
        literal: bool,
        /// What --search matches: name, value or any.
        #[arg(long = "in", value_name = "FIELD", default_value = "any", requires = "search")]
        field: String,
        /// Follow QUERY's reference chain to its final value.
        #[arg(long, requires = "query")]
        resolve: bool,
        /// Write the output to this file instead of stdout.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Path to the input APK (or jar, .dex; or a HarmonyOS .hap, .app); a directory, or paths joined with `,`, read as one program.
        apk_path: PathBuf,
        /// A resource id (0x7f0d0001) or name (string/app_name, @pkg:type/name).
        /// HarmonyOS: an id in hex or decimal (0x01000003, 16777219) or a name
        /// (string/app_name, $string:app_name, app.string.app_name).
        query: Option<String>,
    },
    /// Print a packaged XML or profile file: binary XML decoded (HarmonyOS: a text file as it is).
    ///
    /// Android: any binary XML file of the APK (res/xml/..., layouts), with
    /// resource references shown by name.
    ///
    /// HarmonyOS: print a text file of the package as it is: the page list
    /// and route table module.json names (`$profile:main_pages`,
    /// `$profile:router_map`), any other profile, a rawfile.
    Xml {
        /// Also write the decoded XML to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Path to the input APK (or jar, .dex; or a HarmonyOS .hap, .app); a directory, or paths joined with `,`, read as one program.
        apk_path: PathBuf,
        /// Path inside the APK, e.g. res/xml/network_security_config.xml.
        /// HarmonyOS: a file resource ($profile:main_pages) or a path inside
        /// the package (resources/base/profile/main_pages.json; with the
        /// package ahead of it, entry.hap/resources/..., for one package of several).
        path: String,
    },
    /// Find code references (strings, types, methods, fields; HarmonyOS: strings, properties, imports, calls ...) across all code entries.
    ///
    /// Exits with status 2 when some DEX entries could not be searched; the
    /// results of the other entries are still printed.
    ///
    /// Field results are labelled `[read]` / `[write]`; `--access read` or
    /// `--access write` keeps only that kind.
    ///
    /// HarmonyOS programs take string, prop, global, import, method, number,
    /// call, all and rules. Rows are `entry | record->function+0xPC |
    /// restored name | instruction`; the second column is what getclass takes.
    /// `string` also finds what no instruction holds: `record->function |
    /// name | annotation @RECORD element="..."` for an annotation on a
    /// function, `record field NAME | - | ...` for a record field (the
    /// default of an annotation interface: `annotation default "..."`).
    Findrefs {
        /// Path to the input APK (or jar, .dex; or a HarmonyOS .hap, .app, .abc); a directory, or paths joined with `,`, read as one program.
        apk_path: PathBuf,
        /// After each result, show the referencing instructions (marked `>`)
        /// with N smali lines around them, and their pc / source line; or
        /// `method` for the whole referencing method. HarmonyOS: lines of
        /// the function's listing, as getclass prints it.
        #[arg(long, global = true, value_name = "N|method", value_parser = parse_context, conflicts_with = "context_method")]
        context: Option<RefContext>,
        /// Same as `--context method`.
        #[arg(long, global = true, hide = true)]
        context_method: bool,
        /// For field queries, keep only reads (iget/sget) or writes (iput/sput).
        /// HarmonyOS: for prop and global, also define (own property
        /// definitions) and call (the property is called).
        #[arg(long, global = true, value_enum, value_name = "read|write")]
        access: Option<FieldAccessArg>,
        /// HarmonyOS: search only this ABC entry (ets/widgets.abc) or
        /// package (entry.hap), as the first column names it. A resource
        /// id is unique within one package only.
        #[arg(long, global = true, value_name = "NAME")]
        entry: Option<String>,
        #[command(subcommand)]
        find: Find,
    },
    /// Callers (default) or callees of a method (HarmonyOS: a function), as an indented tree, across all code entries.
    ///
    /// One line per call: depth, `<-` (caller) or `->` (callee), signature.
    /// `[no body]` marks methods no DEX of the APK defines (framework / SDK),
    /// `(repeated)` methods expanded elsewhere in the tree. References are
    /// static: a call through a subclass is not a call of the base method
    /// (unless --virtual).
    ///
    /// The target is CLASS METHOD, or every method whose code matches a
    /// findrefs rule (--to; --from alone walks callees). --to with --from
    /// keeps only the caller paths that start at a --from method (marked
    /// `[from]`); --unless leaves out methods whose code matches a rule.
    ///
    /// HarmonyOS: the target is a function, `[RECORD] FUNCTION` or
    /// `RECORD->FUNCTION` as result rows print it, or `--to call:REGEX`:
    /// the callers of every callee path the regex matches (the paths of
    /// `findrefs call`, e.g. 'call:^import:@ohos:net\.http'); any other
    /// --to rule targets the functions it matches. --from and --unless
    /// take rules as above, with the HarmonyOS conditions (see `findrefs
    /// all`); there `method:NAME` is the function of that name itself
    /// (`--from 'method:^EntryAbility\.on'`). A call names
    /// no callee there, so rows say how each link was made: no mark for a
    /// proved call, `[new]`, `[super]` (the parent's constructor or method),
    /// `[this-class]` / `[inherited]` / `[instance]` (a method matched by
    /// name in the class of the caller, in an ancestor, or in the class of
    /// an object: an exported `new C()`, or what a function such as
    /// `C.getInstance()` returns: not guaranteed), `[reassigned]` (a
    /// class a decorator assigned again: holds if it kept the class),
    /// `[defines]` (a closure is
    /// created, not called); callees that are no function of the program
    /// are leaves: `[external]` (the path starts outside the program: a
    /// system API, a native library, a global), `[unlinked]` (it starts at
    /// an import of the program and led to no function: a member of a call
    /// result, a member no class lists) or `[unresolved]` (the callee is a
    /// value tracking lost); `unresolved=N` counts such call sites of a
    /// function. `[N+ subclasses skipped]`: the class of the method has
    /// more subclasses than a callers walk follows; callers through the
    /// rest were not looked for.
    /// A callback the system calls has no callers.
    Callgraph {
        /// Write the tree to this file instead of stdout.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Walk callees instead of callers.
        #[arg(long)]
        callees: bool,
        /// Levels to expand.
        #[arg(long, default_value_t = 2)]
        depth: usize,
        /// Stop after discovering this many methods.
        #[arg(long, value_name = "N", default_value_t = 500)]
        max_nodes: usize,
        /// Follow virtual dispatch: callers also through the same signature on
        /// each supertype (`(via Lbase;)`), callees also the overrides in
        /// subclasses (`(override of Lbase;)`).
        #[arg(long = "virtual")]
        virtual_calls: bool,
        /// Target: every method whose code matches this findrefs rule, e.g.
        /// 'method:android.telephony.TelephonyManager->getImei'.
        #[arg(long, value_name = "RULE")]
        to: Option<String>,
        /// Keep the caller paths that start at a method whose code matches
        /// this rule; without a target, walk the callees of those methods.
        #[arg(long, value_name = "RULE")]
        from: Option<String>,
        /// Leave out every method whose code matches this rule, and what is
        /// reached only through it (repeatable).
        #[arg(long, value_name = "RULE")]
        unless: Vec<String>,
        /// HarmonyOS: leave out the `[defines]` rows (closures a function
        /// creates, which are not calls) and what is reached only through them.
        #[arg(long)]
        no_defines: bool,
        /// HarmonyOS, with --callees: also list the call sites whose callee
        /// could not be resolved (`[unresolved]`), not only count them.
        #[arg(long)]
        unresolved: bool,
        /// HarmonyOS: take the root function from this ABC entry
        /// (ets/modules.abc), when several define it.
        #[arg(long, value_name = "NAME")]
        entry: Option<String>,
        /// Path to the input APK (or jar, .dex; or a HarmonyOS .hap, .app, .abc); a directory, or paths joined with `,`, read as one program.
        apk_path: PathBuf,
        /// Declaring class (rs.asc.Main or Lrs/asc/Main;). HarmonyOS: a
        /// record (pages/Index), or the whole root as result rows print it
        /// (RECORD->FUNCTION), or a function name alone (Index.build).
        class: Option<String>,
        /// Method name (every overload) or exact signature, e.g. run(I)V.
        /// HarmonyOS: a function, by its restored (Index.build) or raw name.
        #[arg(requires = "class")]
        method: Option<String>,
    },
    /// Class hierarchy across all code entries: transitive subclasses and
    /// implementers (default) or supertypes, as an indented tree.
    ///
    /// One line per class: depth, `subclass` / `implementer` (or `extends` /
    /// `implements` with --supers), descriptor, defining DEX or `[not in APK]`.
    /// With --method, classes defining it are marked `[defines m(..)V]` and
    /// listed as `override Lsub;->m(..)V dex` lines (`inherited` with --supers).
    ///
    /// HarmonyOS: CLASS is a class name (EntryAbility), RECORD->CLASS as rows
    /// print it, or `import:REGEX` / `global:REGEX` for the subclasses of a
    /// parent outside the program (import:@ohos:app\.ability\.UIAbility). Rows
    /// are `RECORD->CONSTRUCTOR | Name`, or a parent's path marked `[external]`
    /// / `[unresolved]`; --method NAME marks `[defines FUNCTION]`.
    Hierarchy {
        /// Write the tree to this file instead of stdout.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Walk superclasses and interfaces instead of subclasses.
        #[arg(long)]
        supers: bool,
        /// Levels to walk.
        #[arg(long, default_value_t = 16)]
        depth: usize,
        /// Stop after discovering this many classes.
        #[arg(long, value_name = "N", default_value_t = 2000)]
        max_nodes: usize,
        /// Mark the classes defining this method: a name or name(params)ret.
        #[arg(long)]
        method: Option<String>,
        /// HarmonyOS: take the class from this ABC entry (ets/modules.abc).
        #[arg(long, value_name = "ENTRY")]
        entry: Option<String>,
        /// Path to the input APK (or jar, .dex); a directory, or paths joined with `,`, read as one program.
        apk_path: PathBuf,
        /// Class in dotted or Dalvik form.
        class: String,
    },
    /// Serve MCP tools over stdio (one JSON-RPC message per line), keeping
    /// opened programs (APKs, HarmonyOS packages) resident across calls.
    /// Every opened program shares one `--memory-mb` budget.
    Mcp {
        /// Refuse a single entry that inflates past this many MiB (zip bombs).
        #[arg(long, default_value_t = 1024)]
        max_entry_mb: u64,
        /// Refuse an entry that expands more than this over its compressed size.
        #[arg(long, default_value_t = 100)]
        max_ratio: u64,
        /// Package prefixes `collapse_sdks` folds, comma separated (rs.asc or
        /// Lrs/asc/), replacing the built-in list.
        #[arg(long, value_delimiter = ',')]
        sdk_prefixes: Option<Vec<String>>,
        /// structuredContent: `compact` leaves out its bulky values (rows,
        /// smali) that the text already carries, since some clients show
        /// the model both; `full` keeps everything.
        #[arg(long, value_enum, default_value_t = StructuredArg::Compact)]
        structured: StructuredArg,
    },
    /// Inspect or clear the on-disk cache of inflated DEX files.
    Cache {
        #[command(subcommand)]
        action: CacheAction,
    },
    /// The per-user daemon that keeps programs (APKs, HarmonyOS packages) resident for one-shot commands.
    ///
    /// Commands start it on first use and answer through it afterwards, with
    /// the same output as without it; it exits after 15 idle minutes.
    /// `ASC_DAEMON=off` runs every command in its own process.
    Daemon {
        #[command(subcommand)]
        action: DaemonAction,
    },
    /// The settings of threads, memory and the disk cache: values, sources and what `auto` is on this machine.
    Config {
        #[command(subcommand)]
        action: Option<settings::ConfigAction>,
        /// One JSON object (for scripts and agents).
        #[arg(long)]
        json: bool,
    },
}

impl Command {
    /// The APK of a one-shot command (`None` for the resident and
    /// maintenance commands).
    fn apk_path(&self) -> Option<&Path> {
        match self {
            Command::Getclass { apk_path, .. }
            | Command::Disassemble { apk_path, .. }
            | Command::Listclass { apk_path, .. }
            | Command::Getmanifest { apk_path, .. }
            | Command::ManifestSummary { apk_path, .. }
            | Command::Resources { apk_path, .. }
            | Command::Xml { apk_path, .. }
            | Command::Findrefs { apk_path, .. }
            | Command::Callgraph { apk_path, .. }
            | Command::Hierarchy { apk_path, .. } => Some(apk_path),
            Command::Mcp { .. } | Command::Cache { .. } | Command::Daemon { .. } | Command::Config { .. } => None,
        }
    }
}

#[derive(Subcommand)]
enum DaemonAction {
    /// Start the daemon of this build and cache configuration (if not running).
    Start,
    /// Stop every daemon of this user.
    Stop,
    /// Show the running daemons.
    Status,
    /// Run the daemon in this process (what `start` spawns).
    #[command(hide = true)]
    Serve,
}

/// `--context`: a number of lines, or `method`.
fn parse_context(s: &str) -> Result<RefContext, String> {
    match s.trim() {
        "method" => Ok(RefContext::Method),
        n => n.parse().map(RefContext::Lines).map_err(|_| format!("{s:?} is neither a number of lines nor `method`")),
    }
}

/// `mcp --structured`.
#[derive(Clone, Copy, ValueEnum)]
enum StructuredArg {
    Compact,
    Full,
}

#[derive(Clone, Copy, ValueEnum)]
enum FieldAccessArg {
    Read,
    Write,
    /// HarmonyOS only.
    Define,
    /// HarmonyOS only.
    Call,
}

impl TryFrom<FieldAccessArg> for asc_findrefs::FieldAccess {
    type Error = String;

    fn try_from(access: FieldAccessArg) -> Result<Self, String> {
        match access {
            FieldAccessArg::Read => Ok(asc_findrefs::FieldAccess::Read),
            FieldAccessArg::Write => Ok(asc_findrefs::FieldAccess::Write),
            FieldAccessArg::Define => Err(harmony_only("--access define")),
            FieldAccessArg::Call => Err(harmony_only("--access call")),
        }
    }
}

#[derive(Subcommand)]
enum CacheAction {
    /// Print the cache directory.
    Path,
    /// Print how much is cached.
    Stats,
    /// Delete every cached file.
    Clear,
}

#[derive(Subcommand)]
enum Find {
    /// Find references to a fuzzy string (regex).
    String {
        /// Also write every result to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Match VALUE as a plain substring instead of a regex.
        #[arg(long)]
        literal: bool,
        /// Fuzzy string pattern.
        value: String,
    },
    /// Find references to a fuzzy type descriptor/name.
    Type {
        /// Also write every result to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Fuzzy type pattern.
        value: String,
    },
    /// Find classes that extend the target class.
    Extends {
        /// Also write every result to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Target class in dotted or Dalvik form, e.g. android.app.Activity or Lrs/asc/Base;.
        value: String,
    },
    /// Find classes that implement the target interface.
    Impl {
        /// Also write every result to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Target interface in dotted or Dalvik form, e.g. android.os.IInterface.
        value: String,
    },
    /// Find references to methods.
    Method {
        /// Also write every result to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Fuzzy method name, or the whole target: Lrs/asc/B;->name,
        /// rs.asc.B.name, rs.asc.B#name, B.name (any package); or '{RULE}'
        /// (calls of the methods whose code matches RULE) or @FILE (of the
        /// methods FILE lists).
        name: Option<String>,
        /// Dalvik class or fuzzy class pattern.
        #[arg(long = "class")]
        class_name: Option<String>,
        /// Treat --class as fuzzy match.
        #[arg(long)]
        fuzzy_class: bool,
        /// Match the name exactly instead of as a substring / regex.
        #[arg(long)]
        exact: bool,
    },
    /// Find methods whose code matches every condition (and none of --none),
    /// e.g. `all string:http:// method:android.webkit.WebView->loadUrl`.
    ///
    /// Conditions are KIND:VALUE: string:REGEX, literal:TEXT, type:PATTERN,
    /// method:TARGET, field:TARGET. TARGET is [CLASS->]NAME, also written
    /// rs.asc.B.name or rs.asc.B#name (CLASS exact, `~CLASS` fuzzy, without
    /// package any package; NAME a regex / substring, `=NAME` or a name
    /// with its signature exact). method:{RULE} is a call of any method whose
    /// code matches RULE (a rule as for `rules`), method:@FILE of any method
    /// FILE lists (one per line; findrefs output works). `!CONDITION` is
    /// one more --none. The last column lists what each condition matched,
    /// in order.
    ///
    /// HarmonyOS: the conditions are string:REGEX, literal:TEXT, prop:NAME,
    /// global:NAME, import:REQUEST[#NAME], number:N, call:PATH-REGEX and
    /// method:[RECORD->]NAME (NAME a regex, `=NAME` exact). Among several
    /// conditions method: is the function of that name itself (alone: where
    /// it is defined). call:{RULE} is a call that leads to a function whose
    /// code matches RULE, call:{@FILE} to a function FILE lists (one per
    /// line; findrefs and callgraph output works).
    All {
        /// Also write every result to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Drop methods that also match this condition (repeatable).
        #[arg(long, value_name = "CONDITION")]
        none: Vec<String>,
        /// Conditions that must all match in one method.
        #[arg(required = true)]
        conditions: Vec<String>,
    },
    /// Run several queries in one pass over each DEX, rows prefixed by rule
    /// (`r1 | dex | ...`), after a `# r1 ...` header per rule.
    ///
    /// Each rule is a condition as for `all` (also extends:CLASS,
    /// impl:CLASS), or several joined with `&` for a compound rule, `!`
    /// before the ones a method must not match. `&` inside `{}` or `()`, or
    /// written `\&`, belongs to its condition.
    ///
    /// HarmonyOS: the conditions of `all`; a `&` joins only ahead of
    /// `KIND:` (record names hold `&`). Each rule is one search.
    Rules {
        /// Also write every result to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Read more rules from this file, one per line (`#` comments).
        #[arg(long)]
        file: Option<PathBuf>,
        /// The rules.
        rules: Vec<String>,
    },
    /// HarmonyOS: find property accesses by name (`obj.NAME`, `this.NAME`,
    /// `obj.NAME(...)`), labelled `[read]` / `[write]` / `[define]` /
    /// `[call]`; `--access` keeps one kind. A method call is one `[call]`
    /// row: the load of the method, or the call itself when it names the
    /// method (`callthisNwithname`).
    Prop {
        /// Also write every result to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Match NAME as a plain substring instead of a regex.
        #[arg(long, conflicts_with = "exact")]
        literal: bool,
        /// Match the whole name instead of a regex.
        #[arg(long)]
        exact: bool,
        /// Property name pattern (regex; `=NAME` is --exact).
        name: String,
    },
    /// HarmonyOS: find reads and writes of global bindings by name
    /// (`console`, `globalThis.NAME`), labelled `[read]` / `[write]`.
    Global {
        /// Also write every result to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Match NAME as a plain substring instead of a regex.
        #[arg(long, conflicts_with = "exact")]
        literal: bool,
        /// Match the whole name instead of a regex.
        #[arg(long)]
        exact: bool,
        /// Global name pattern (regex; `=NAME` is --exact).
        name: String,
    },
    /// HarmonyOS: find uses of imported bindings: the import declarations of
    /// each record and the instructions that load the binding.
    Import {
        /// Also write every result to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Match REQUEST as a plain substring instead of a regex.
        #[arg(long)]
        literal: bool,
        /// Only the import declarations, one row each; no code is scanned.
        #[arg(long, conflicts_with = "requests")]
        decl: bool,
        /// Only the distinct module requests: `request | N records | imported names`.
        #[arg(long)]
        requests: bool,
        /// REQUEST or REQUEST#NAME: a regex over the module request
        /// (@ohos:net.http, @normalized:N&&&entry/src/main/ets/pages/Index&),
        /// then the imported name (default, request; `*` is the namespace).
        value: String,
    },
    /// HarmonyOS: find numeric constants: `ldai`, `fldai` and the numbers of
    /// array and object literals.
    Number {
        /// Also write every result to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// 1919810, -1, 0x1d4b42, 1.5, or a range A..B. A 32-bit value
        /// with the top bit set also finds its negative spelling
        /// (0x9e3779b9 finds ldai -1640531527).
        #[arg(allow_hyphen_values = true)]
        value: String,
    },
    /// HarmonyOS: find call sites by resolved callee path, with the known
    /// argument values: `callthis1 ... ; import:@ohos:net.http#default.createHttp("...")`.
    ///
    /// The callee is tracked inside a basic block. Paths start with
    /// import:REQUEST#NAME, global:NAME, globalThis, this, super, local:FUNCTION
    /// (defined here), module:NAME (module-level binding); where tracking
    /// stops they say why: lex(LEVEL,SLOT) is a captured variable, argN a
    /// parameter, expr a computed value, `?` a value set in another block.
    /// `X().member` is a member of what calling X returned:
    /// import:@ohos:net.http#default.createHttp().request.
    Call {
        /// Also write every result to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Match PATH as a plain substring instead of a regex.
        #[arg(long)]
        literal: bool,
        /// Callee path pattern (regex), e.g. 'import:@ohos:net\.http.*\.request$';
        /// or '{RULE}': the calls that lead to a function whose code
        /// matches RULE (a rule as for `all`), '{@FILE}' to one FILE lists.
        path: String,
    },
    /// Find references to fields.
    Field {
        /// Also write every result to this file.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Fuzzy field name, or the whole target: Lrs/asc/B;->name,
        /// rs.asc.B.name, rs.asc.B#name, B.name (any package).
        name: Option<String>,
        /// Dalvik class or fuzzy class pattern.
        #[arg(long = "class")]
        class_name: Option<String>,
        /// Treat --class as fuzzy match.
        #[arg(long)]
        fuzzy_class: bool,
        /// Match the name exactly instead of as a substring / regex.
        #[arg(long)]
        exact: bool,
    },
}

impl Find {
    /// The kind, when only a HarmonyOS program has it: the subcommand, or
    /// the first such `KIND:` among the conditions of `all`.
    fn harmony_only(&self) -> Option<&'static str> {
        const CONDITIONS: [&str; 5] = ["prop:", "global:", "import:", "number:", "call:"];
        match self {
            Find::Prop { .. } => Some("prop"),
            Find::Global { .. } => Some("global"),
            Find::Import { .. } => Some("import"),
            Find::Number { .. } => Some("number"),
            Find::Call { .. } => Some("call"),
            Find::All { none, conditions, .. } => {
                let mut specs = conditions.iter().chain(none).map(|spec| spec.strip_prefix('!').unwrap_or(spec));
                specs.find_map(|spec| CONDITIONS.into_iter().find(|kind| spec.starts_with(kind)))
            }
            Find::String { .. }
            | Find::Type { .. }
            | Find::Extends { .. }
            | Find::Impl { .. }
            | Find::Method { .. }
            | Find::Rules { .. }
            | Find::Field { .. } => None,
        }
    }
}

/// `findrefs rules`: every rule in one pass, rows prefixed `rN | `.
#[allow(clippy::too_many_arguments)] // one call site, each argument a CLI option
fn findrefs_rules(
    io: &mut Io<'_>,
    common: &Common,
    apk_path: &Path,
    context: RefContext,
    output: Option<PathBuf>,
    file: Option<PathBuf>,
    mut specs: Vec<String>,
    t_start: Instant,
) -> Result<u8, String> {
    if let Some(f) = &file {
        let text = std::fs::read_to_string(io.path(f)).map_err(|e| format!("cannot read {}: {e}", f.display()))?;
        specs.extend(text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).map(String::from));
    }
    if specs.is_empty() {
        return Err("findrefs rules needs at least one rule".into());
    }
    let rules = specs.iter().map(|spec| io.rule(spec)).collect::<Result<Vec<_>, _>>()?;
    let engine = io.engine(common, apk_path);
    let cancel = io.cancel;
    let mut order = DexOrder::new(&engine, rules.len())?;
    let mut sink = io.sink(output.as_ref(), true)?;
    for (i, spec) in specs.iter().enumerate() {
        sink.comment(&format!("# r{} {spec}", i + 1));
    }
    let mut errors = Vec::new();
    let mut totals = vec![0usize; rules.len()];
    let opts = FindOptions { aggregate: true, context };
    let mut print = |(i, batch): (usize, asc_engine::RefBatch), sink: &mut output::LineSink<_>| {
        if let Some(e) = batch.error {
            errors.push(format!("{}: {e}", batch.entry_name));
        }
        totals[i] += batch.results.len();
        for r in &batch.results {
            let record: Vec<String> = r
                .text()
                .lines()
                .enumerate()
                .map(|(j, line)| if j == 0 { format!("r{} | {line}", i + 1) } else { format!("r{} |{line}", i + 1) })
                .collect();
            sink.line(&record.join("\n"));
        }
    };
    let summary = engine
        .find_refs_rules(&rules, opts, cancel, &mut |i, batch| {
            let name = batch.entry_name.clone();
            for item in order.push(&name, i, (i, batch)) {
                print(item, &mut sink);
            }
            sink.flush_stdout();
        })
        .map_err(|e| e.to_string())?;
    for item in order.finish() {
        print(item, &mut sink);
    }
    for (i, n) in totals.iter().enumerate() {
        sink.comment(&format!("# r{} {n} results", i + 1));
    }
    for n in &summary.notes {
        sink.comment(&format!("# {n}"));
    }
    let io_result = sink.finish();
    errors.sort();
    errors.dedup();
    for e in &errors {
        io.note(format_args!("Warning: {e}"));
    }
    for (i, (n, rule)) in totals.iter().zip(&rules).enumerate() {
        if let Some(h) = (*n == 0).then(|| asc_engine::hints::query_hint(rule)).flatten() {
            io.note(format_args!("hint: r{}: {h}", i + 1));
        }
    }
    if common.debug {
        io.note(format_args!("[DEBUG] Total Execution Time: {} us", t_start.elapsed().as_micros()));
    }
    io_result?;
    Ok(if errors.is_empty() { EXIT_OK } else { EXIT_PARTIAL })
}

/// A findrefs run's batches in DEX order (`classes.dex`, `classes2.dex`, ...,
/// then other names), whatever order the workers finish in. An entry's
/// batches (one per rule, `parts` in all) wait until every earlier entry is
/// complete, so the output is the same on every run and still streams as
/// soon as the order allows.
struct DexOrder<T> {
    order: Vec<String>,
    next: usize,
    parts: usize,
    pending: HashMap<String, Vec<(usize, T)>>,
}

impl<T> DexOrder<T> {
    fn new(engine: &Engine, parts: usize) -> Result<DexOrder<T>, String> {
        let mut order: Vec<String> = engine.dex_entries().map_err(|e| e.to_string())?.into_iter().map(|e| e.name).collect();
        order.sort_by(|a, b| dex_rank(a).cmp(&dex_rank(b)));
        Ok(DexOrder { order, next: 0, parts, pending: HashMap::new() })
    }

    /// Take `item` (part `part` of `entry`); the items now due, in order.
    fn push(&mut self, entry: &str, part: usize, item: T) -> Vec<T> {
        self.pending.entry(entry.to_string()).or_default().push((part, item));
        let mut due = Vec::new();
        while let Some(name) = self.order.get(self.next) {
            if self.pending.get(name).is_none_or(|items| items.len() < self.parts) {
                break;
            }
            if let Some(items) = self.pending.remove(name) {
                due.extend(by_part(items));
            }
            self.next += 1;
        }
        due
    }

    /// Everything still held (entries a cancelled or replayed run left
    /// incomplete), in order.
    fn finish(mut self) -> Vec<T> {
        let mut names: Vec<String> = self.pending.keys().cloned().collect();
        names.sort_by(|a, b| dex_rank(a).cmp(&dex_rank(b)));
        names.into_iter().filter_map(|n| self.pending.remove(&n)).flat_map(by_part).collect()
    }
}

fn by_part<T>(mut items: Vec<(usize, T)>) -> impl Iterator<Item = T> {
    items.sort_by_key(|(part, _)| *part);
    items.into_iter().map(|(_, item)| item)
}

/// Sort key of a DEX entry name: `classes.dex`, `classes2.dex`, ... by
/// number, then every other name alphabetically.
fn dex_rank(name: &str) -> (u8, u64, &str) {
    match name.strip_prefix("classes").and_then(|rest| rest.strip_suffix(".dex")) {
        Some("") => (0, 1, name),
        Some(n) if !n.starts_with('0') => n.parse().map_or((1, 0, name), |k| (0, k, name)),
        _ => (1, 0, name),
    }
}

/// Arguments shared by `getclass` and `disassemble`, which differ (as in
/// Python) in whether debug directives are on by default and whether `-o`
/// also prints to stdout.
struct ClassArgs {
    output: Option<PathBuf>,
    /// Print to stdout even with `-o`.
    tee: bool,
    debug_info: bool,
    dump_dex: Option<PathBuf>,
    method_signature: Option<String>,
    res_names: bool,
    /// `--entry`: the ABC entry of a HarmonyOS program to look in.
    entry: Option<String>,
    /// `--lines`: every line change in the listing of a HarmonyOS program.
    lines: bool,
    apk_path: PathBuf,
    dalvik_class: String,
}

/// The class, or only the methods `method` names: an exact signature is
/// rendered on its own; a name, a signature prefix or a Java-style signature
/// is picked from the whole class (as MCP `getclass` does).
fn class_methods(
    engine: &Engine,
    descriptor: &str,
    opts: asc_engine::SmaliOptions,
    method: Option<&str>,
    cancel: &AtomicBool,
) -> Result<asc_engine::ClassSource, String> {
    // `name(params)ret`: what the engine renders on its own.
    let full_signature = |m: &&str| m.split_once(')').is_some_and(|(head, ret)| head.contains('(') && !ret.trim().is_empty());
    if let Some(m) = method.filter(full_signature)
        && let Ok(src) = engine.get_class_method_cancellable(descriptor, opts, Some(m), cancel)
    {
        return Ok(src);
    }
    let mut src = engine.get_class_method_cancellable(descriptor, opts, None, cancel).map_err(|e| e.to_string())?;
    if let Some(m) = method {
        let parsed = asc_mcp::class_text::ClassText::parse(&src.source);
        let picked = parsed.select(m);
        if picked.is_empty() {
            return Err(format!("{descriptor} has no method {m:?}; its methods: {}", parsed.signatures(4 << 10)));
        }
        let text = parsed.with_methods(&picked);
        src.source = text;
    }
    Ok(src)
}

fn getclass(io: &mut Io<'_>, common: &Common, args: ClassArgs, t_start: Instant) -> Result<(), String> {
    if args.entry.is_some() {
        return Err(HARMONY_ONLY_ENTRY.into());
    }
    if args.lines {
        return Err(harmony_only("--lines"));
    }
    let descriptor = names::format_class_name(&args.dalvik_class).map_err(|e| e.to_string())?;
    let engine = io.engine(common, &args.apk_path);
    let opts = asc_engine::SmaliOptions { line_numbers: args.debug_info, param_names: args.debug_info };
    let mut src = class_methods(&engine, &descriptor, opts, args.method_signature.as_deref(), io.cancel)?;
    if args.res_names {
        src.source = engine.annotate_resource_ids(&src.source);
    }
    if let Some(w) = &src.warning {
        io.note(format_args!("Warning: {w}"));
    }
    if !src.also_defined_in.is_empty() {
        io.note(format_args!("# {descriptor} from {}; also defined in {}", src.dex_name, src.also_defined_in.join(", ")));
    }
    if let Some(p) = &args.dump_dex {
        let rebuilt = src.rebuilt.as_ref().ok_or_else(|| format!("cannot write {}: the class was not rebuilt", p.display()))?;
        io.write_file(p, &rebuilt.bytes)?;
    }
    if common.debug {
        io.note(format_args!("[DEBUG] Hit DEX: {}", src.dex_name));
        io.note(format_args!("[DEBUG] APK Scan Time: {} us", src.scan_us));
        if let Some(r) = &src.rebuilt {
            io.note(format_args!(
                "[DEBUG] Rebuilt DEX: {} bytes, {} strings, {} types, {} protos, {} fields, {} methods ({} with code)",
                r.stats.size, r.stats.strings, r.stats.types, r.stats.protos, r.stats.fields, r.stats.methods, r.stats.methods_with_code
            ));
        }
        io.note(format_args!("[DEBUG] Total Execution Time: {} us", t_start.elapsed().as_micros()));
        io.note("-".repeat(50));
    }
    io.write_output(args.output.as_ref(), &src.source)?;
    if args.output.is_some() && !args.tee {
        return Ok(());
    }
    io.emit_records(&src.source, args.output.as_ref())
}

/// Run a one-shot command (everything but `mcp`, `cache` and `daemon`,
/// which [`run`] handles itself) against `io`: the exit status.
fn run_query(io: &mut Io<'_>, common: &Common, command: Command, t_start: Instant) -> Result<u8, String> {
    io.window = common.window();
    io.spill = common.spill();
    if let Some(apk_path) = command.apk_path() {
        for note in io.engine(common, apk_path).program_notes() {
            io.note(format_args!("# warning: {note}"));
        }
        if let Some(note) = left_out_note(&io.program_path(apk_path)) {
            io.note(format_args!("# warning: {note}"));
        }
    }
    match command {
        Command::Getclass { output, no_debug_info, dump_dex, method_signature, res_names, entry, lines, apk_path, dalvik_class } => {
            let debug_info = !no_debug_info;
            let args =
                ClassArgs { output, tee: true, debug_info, dump_dex, method_signature, res_names, entry, lines, apk_path, dalvik_class };
            getclass(io, common, args, t_start)?;
        }
        Command::Disassemble { output, debuginfo, method_signature, res_names, dump_dex, entry, lines, apk_path, dalvik_class } => {
            let debug_info = debuginfo;
            let args =
                ClassArgs { output, tee: false, debug_info, dump_dex, method_signature, res_names, entry, lines, apk_path, dalvik_class };
            getclass(io, common, args, t_start)?;
        }
        Command::Listclass { prefix, all, entry, output, apk_path } => {
            if all {
                return Err(HARMONY_ONLY_ALL.into());
            }
            if entry.is_some() {
                return Err(HARMONY_ONLY_ENTRY.into());
            }
            let classes = io.engine(common, &apk_path).list_classes(prefix.as_deref()).map_err(|e| e.to_string())?;
            let mut text = String::with_capacity(classes.iter().map(|c| c.descriptor.len() + 1).sum());
            for c in &classes {
                text.push_str(&c.descriptor);
                // A program of several archives also names the one defining it.
                if let Some(archive) = asc_engine::archive_of(&c.dex_name) {
                    text.push_str(" | ");
                    text.push_str(archive);
                }
                text.push('\n');
            }
            match &output {
                Some(p) => io.write_file(p, text.as_bytes())?,
                None if text.is_empty() => {}
                None => io.emit_records(&text, None)?,
            }
            if common.debug {
                io.note(format_args!("[DEBUG] Total Execution Time: {} us", t_start.elapsed().as_micros()));
            }
        }
        Command::Getmanifest { output, resolve, file, apk_path } => {
            if file.is_some() {
                return Err(harmony_only("--file"));
            }
            let engine = io.engine(common, &apk_path);
            let xml = if resolve { engine.manifest_xml_resolved() } else { engine.manifest_xml() }.map_err(|e| e.to_string())?;
            io.write_output(output.as_ref(), &xml)?;
            io.emit_records(&xml, output.as_ref())?;
            if common.debug {
                io.note(format_args!("[DEBUG] Total Execution Time: {} us", t_start.elapsed().as_micros()));
            }
        }
        Command::ManifestSummary { json, output, file, apk_path } => {
            if file.is_some() {
                return Err(harmony_only("--file"));
            }
            let summary = io.engine(common, &apk_path).manifest_summary().map_err(|e| e.to_string())?;
            let text = if json { format!("{:#}", summary.json()) } else { summary.lines().join("\n") };
            io.write_output(output.as_ref(), &text)?;
            io.emit_records(&text, output.as_ref())?;
        }
        Command::Resources { search, literal, field, resolve, output, apk_path, query } => {
            let engine = io.engine(common, &apk_path);
            let mut note = None;
            // With a window every match goes through it (the file holds them all).
            let search_cap = if output.is_none() && !io.window.is_everything() { usize::MAX } else { RESOURCE_SEARCH_ROWS };
            let mut sink = io.sink(output.as_ref(), output.is_none())?;
            match (search, query) {
                (Some(pattern), _) => {
                    let field = match field.as_str() {
                        "name" => asc_engine::ResourceField::Name,
                        "value" => asc_engine::ResourceField::Value,
                        "any" => asc_engine::ResourceField::Any,
                        other => return Err(format!("--in must be name, value or any, not {other}")),
                    };
                    let (rows, total) = engine.search_resources(&pattern, literal, field, search_cap).map_err(|e| e.to_string())?;
                    rows.iter().for_each(|r| sink.line(&r.line()));
                    if total > rows.len() {
                        note = Some(format!(
                            "Note: {} of {total} matches shown; with --limit or --max-bytes every match goes to a file",
                            rows.len()
                        ));
                    }
                }
                (None, Some(q)) if resolve => {
                    let (chain, row) = engine.resolve_resource(&q, None).map_err(|e| e.to_string())?;
                    sink.line(&format!("chain {}", chain.join(" -> ")));
                    sink.line(&row.line());
                }
                (None, Some(q)) => engine.resource(&q).map_err(|e| e.to_string())?.iter().for_each(|r| sink.line(&r.line())),
                (None, None) => engine.dump_resources(|r| sink.line(&r.line())).map_err(|e| e.to_string())?,
            }
            let io_result = sink.finish();
            if let Some(n) = note {
                io.note(n);
            }
            io_result?;
        }
        Command::Xml { output, apk_path, path } => {
            let xml = io.engine(common, &apk_path).xml(&path).map_err(|e| e.to_string())?;
            io.write_output(output.as_ref(), &xml)?;
            io.emit_records(&xml, output.as_ref())?;
        }
        Command::Findrefs { apk_path, context, context_method, access, entry, find } => {
            if entry.is_some() {
                return Err(HARMONY_ONLY_ENTRY.into());
            }
            let context = match (context, context_method) {
                (Some(c), _) => c,
                (None, true) => RefContext::Method,
                (None, false) => RefContext::None,
            };
            if let Some(kind) = find.harmony_only() {
                return Err(harmony_only(&format!("findrefs {kind}")));
            }
            if access.is_some() && !matches!(&find, Find::Field { .. }) {
                return Err("--access is only valid for `findrefs field`".into());
            }
            if let Find::Rules { output, file, rules } = find {
                return findrefs_rules(io, common, &apk_path, context, output, file, rules, t_start);
            }
            let (query, output) = match find {
                Find::Rules { .. } => unreachable!("handled above"),
                Find::Prop { .. } | Find::Global { .. } | Find::Import { .. } | Find::Number { .. } | Find::Call { .. } => {
                    unreachable!("handled above")
                }
                Find::All { output, none, conditions } => {
                    // `!COND` among the conditions is one more --none.
                    let (excluded, conditions): (Vec<String>, Vec<String>) = conditions.into_iter().partition(|c| c.starts_with('!'));
                    let parse =
                        |c: &[String]| c.iter().map(|c| io.condition(c.strip_prefix('!').unwrap_or(c))).collect::<Result<Vec<_>, _>>();
                    let mut all = parse(&conditions)?;
                    let mut none = parse(&none)?;
                    none.extend(parse(&excluded)?);
                    // One condition is that query itself (`all 'method:{...}'`).
                    if all.len() == 1 && none.is_empty() {
                        (all.pop().expect("one condition"), output)
                    } else {
                        (Query::All { all, none }, output)
                    }
                }
                Find::String { output, literal: false, value } => (Query::String(value), output),
                Find::String { output, literal: true, value } => (Query::StringLiteral(value), output),
                Find::Type { output, value } => (Query::Type(value), output),
                // The class-def lookups need the precise Dalvik form.
                Find::Extends { output, value } => (Query::Extends(names::format_class_name(&value).map_err(|e| e.to_string())?), output),
                Find::Impl { output, value } => (Query::Implements(names::format_class_name(&value).map_err(|e| e.to_string())?), output),
                // `method '{RULE}'` / `method @FILE` (`={...}` / `=@FILE` without
                // dispatch) / `method 'X[arg0=1]'`, as in a condition.
                Find::Method { output, name: Some(name), class_name: None, .. }
                    if name.trim_start_matches(['=', '*']).starts_with(['{', '@']) || asc_engine::condition::has_constraints(&name) =>
                {
                    (io.condition(&format!("method:{name}"))?, output)
                }
                Find::Method { output, name, class_name, fuzzy_class, exact } => (
                    Query::Method(
                        names::member_query("method", class_name.as_deref(), fuzzy_class, name.as_deref(), exact)
                            .map_err(|e| e.to_string())?,
                    ),
                    output,
                ),
                Find::Field { output, name, class_name, fuzzy_class, exact } => {
                    let field = names::member_query("field", class_name.as_deref(), fuzzy_class, name.as_deref(), exact)
                        .map_err(|e| e.to_string())?;
                    let query = match access {
                        Some(access) => Query::FieldAccess { field, access: access.try_into()? },
                        None => Query::Field(field),
                    };
                    (query, output)
                }
            };
            let engine = io.engine(common, &apk_path);
            let cancel = io.cancel;
            let mut order = DexOrder::new(&engine, 1)?;
            let mut sink = io.sink(output.as_ref(), true)?;
            let mut errors = Vec::new();
            let mut print = |batch: asc_engine::RefBatch, sink: &mut output::LineSink<_>| {
                if let Some(e) = batch.error {
                    errors.push(format!("{}: {e}", batch.entry_name));
                }
                if let Some(text) = &batch.text
                    && !sink.block(text.as_str(), text.len())
                {
                    for line in text.lines() {
                        sink.line(line);
                    }
                }
                for r in &batch.results {
                    sink.line(&r.text());
                }
            };
            let mut on_batch = |batch: asc_engine::RefBatch| {
                let name = batch.entry_name.clone();
                for b in order.push(&name, 0, batch) {
                    print(b, &mut sink);
                }
                sink.flush_stdout();
            };
            // Without a context every row is one line: take them as text.
            let summary = match context {
                RefContext::None => engine.find_refs_text(&query, cancel, &mut on_batch),
                _ => engine.find_refs_opts(&query, FindOptions { aggregate: true, context }, cancel, &mut on_batch),
            }
            .map_err(|e| e.to_string())?;
            for b in order.finish() {
                print(b, &mut sink);
            }
            for n in &summary.notes {
                sink.comment(&format!("# {n}"));
            }
            let io_result = sink.finish();
            for e in &errors {
                io.note(format_args!("Warning: {e}"));
            }
            if summary.total_results == 0 && errors.is_empty() {
                for h in engine.no_results_hints(&query, summary.entries) {
                    io.note(format_args!("hint: {h}"));
                }
            }
            if common.debug {
                let st = engine.cache_stats();
                io.note(format_args!("[DEBUG] Cache: {} inflated, {} disk hits, {} skipped", st.inflates, st.disk_hits, st.skipped));
                io.note(format_args!("[DEBUG] Total Execution Time: {} us", t_start.elapsed().as_micros()));
            }
            io_result?;
            if !errors.is_empty() {
                io.note(format_args!(
                    "Warning: {} DEX entr{} could not be searched",
                    errors.len(),
                    if errors.len() == 1 { "y" } else { "ies" }
                ));
                return Ok(EXIT_PARTIAL);
            }
        }
        Command::Callgraph {
            output,
            callees,
            depth,
            max_nodes,
            virtual_calls,
            to,
            from,
            unless,
            no_defines,
            unresolved,
            entry,
            apk_path,
            class,
            method,
        } => {
            if no_defines {
                return Err(harmony_only("--no-defines"));
            }
            if unresolved {
                return Err(harmony_only("--unresolved"));
            }
            if entry.is_some() {
                return Err(HARMONY_ONLY_ENTRY.into());
            }
            let target = match (class, method, to) {
                (None, None, None) => None,
                (None, None, Some(to)) => Some(CallRoots::Matching(io.rule(&to)?)),
                (Some(class), Some(method), None) => {
                    Some(CallRoots::Method { class: names::format_class_name(&class).map_err(|e| e.to_string())?, method })
                }
                (Some(_), None, None) | (None, Some(_), None) => return Err("callgraph needs the METHOD after the CLASS".into()),
                (_, _, Some(_)) => return Err("give the target as CLASS METHOD or as --to RULE, not both".into()),
            };
            let from = from.map(|f| io.rule(&f)).transpose()?;
            let (roots, direction, from) = match (target, from) {
                (Some(roots), from) => (roots, if callees { Direction::Callees } else { Direction::Callers }, from),
                (None, Some(from)) => (CallRoots::Matching(from), Direction::Callees, None),
                (None, None) => return Err("callgraph needs a target: CLASS METHOD, --to RULE or --from RULE".into()),
            };
            let unless = unless.iter().map(|u| io.rule(u)).collect::<Result<Vec<_>, _>>()?;
            let engine = io.engine(common, &apk_path);
            let q = CallQuery { depth, max_nodes, virtual_calls, from, unless, ..CallQuery::new(roots, direction) };
            let tree = engine.call_graph_cancellable(&q, io.cancel).map_err(|e| e.to_string())?;
            io.emit_tree(output.as_ref(), &tree.lines(), &tree.footer())?;
            for e in &tree.errors {
                io.note(format_args!("Warning: {e}"));
            }
            if common.debug {
                io.note(format_args!("[DEBUG] Total Execution Time: {} us", t_start.elapsed().as_micros()));
            }
            if !tree.errors.is_empty() {
                return Ok(EXIT_PARTIAL);
            }
        }
        Command::Hierarchy { output, supers, depth, max_nodes, method, entry, apk_path, class } => {
            if entry.is_some() {
                return Err(HARMONY_ONLY_ENTRY.into());
            }
            let class = names::format_class_name(&class).map_err(|e| e.to_string())?;
            let direction = if supers { Lineage::Supers } else { Lineage::Subclasses };
            let q = HierarchyQuery { class, direction, depth, max_nodes, method };
            let tree = io.engine(common, &apk_path).hierarchy_cancellable(&q, io.cancel).map_err(|e| e.to_string())?;
            let rows: Vec<String> = tree.lines().into_iter().chain(tree.definition_lines()).collect();
            io.emit_tree(output.as_ref(), &rows, &tree.footer())?;
            for e in &tree.errors {
                io.note(format_args!("Warning: {e}"));
            }
            if !tree.errors.is_empty() {
                return Ok(EXIT_PARTIAL);
            }
        }
        Command::Mcp { .. } | Command::Cache { .. } | Command::Daemon { .. } | Command::Config { .. } => {
            unreachable!("run handles the resident and maintenance commands")
        }
    }
    Ok(EXIT_OK)
}

fn run(cli: Cli, t_start: Instant) -> Result<u8, String> {
    let common = cli.common;
    match cli.command {
        Command::Mcp { max_entry_mb, max_ratio, sdk_prefixes, structured } => {
            let spill_bytes = common.config().cache_spill.value.0;
            let mut opts = asc_mcp::Options::new(common.config().fixed_threads(), common.debug, common.resident_cache());
            opts.limits.max_entry_bytes = max_entry_mb.saturating_mul(1 << 20);
            opts.limits.max_ratio = max_ratio;
            if let Some(p) = sdk_prefixes {
                opts.sdk_prefixes = p;
            }
            opts.structured = match structured {
                StructuredArg::Compact => asc_mcp::output::Structured::Compact,
                StructuredArg::Full => asc_mcp::output::Structured::Full,
            };
            if spill_bytes == 0 {
                opts.spill_dir = None;
            }
            opts.spill_bytes = spill_bytes;
            asc_mcp::serve(std::io::stdin().lock(), std::io::stdout(), opts).map_err(|e| format!("mcp: {e}"))?;
        }
        Command::Cache { action } => {
            let Some(cache) = common.disk_cache() else { return Err("no cache directory could be determined".into()) };
            match action {
                CacheAction::Path => println!("{}", cache.dir().display()),
                CacheAction::Stats => {
                    let (apks, files, bytes) = cache.stats();
                    println!("{}\n{apks} APKs, {files} files, {}", cache.dir().display(), mib(bytes));
                    for (tier, t) in asc_engine::asc_cache::Tier::ALL.into_iter().zip(cache.tier_stats()) {
                        println!("  {:12} {} APKs, {} files, {}", tier.label(), t.apks, t.files, mib(t.bytes));
                    }
                    let budget = cache.budget();
                    let source = match budget.capacity {
                        DiskCapacity::Auto(_) => "auto",
                        DiskCapacity::Fixed(_) => "explicit",
                    };
                    println!("budget: {} ({source}), used {}", mib(budget.cap_bytes), mib(budget.used));
                    match budget.space {
                        Some((free, total)) => println!("file system: {} free of {}", mib(free), mib(total)),
                        None => println!("file system: free space unknown"),
                    }
                }
                CacheAction::Clear => {
                    let bytes = cache.clear().map_err(|e| e.to_string())?;
                    println!("freed {}", mib(bytes));
                }
            }
        }
        Command::Daemon { action } => return daemon_command(&common, action),
        Command::Config { action, json } => return settings::print(common.config(), action.as_ref(), json),
        command => {
            // Not locked: engine threads log to stderr themselves (`--debug`).
            let (mut out, mut err) = (std::io::stdout(), std::io::stderr());
            let cancel = AtomicBool::new(false);
            let mut io = Io::new(&mut out, &mut err, &LocalEngines, &cancel);
            // A command without a program is none of these.
            let format = command.apk_path().map_or(ProgramFormat::Android, ProgramFormat::of);
            return run_program(&mut io, &common, command, format, t_start);
        }
    }
    Ok(EXIT_OK)
}

#[cfg(unix)]
fn daemon_command(common: &Common, action: DaemonAction) -> Result<u8, String> {
    daemon::command(common, &action)
}

#[cfg(not(unix))]
fn daemon_command(_common: &Common, _action: DaemonAction) -> Result<u8, String> {
    Err("the daemon needs Unix sockets; commands run in their own process".into())
}

fn mib(bytes: u64) -> String {
    format!("{:.1} MiB", bytes as f64 / (1024.0 * 1024.0))
}

fn main() -> ExitCode {
    let t_start = Instant::now();
    let parsed = Cli::try_parse();
    // clap exits 2 on usage errors, which would collide with `EXIT_PARTIAL`;
    // usage errors are ordinary errors (1), help/version are not errors (0).
    let mut cli = match parsed {
        Ok(cli) => cli,
        Err(e) => {
            let _ = e.print();
            return if e.use_stderr() { ExitCode::from(1) } else { ExitCode::SUCCESS };
        }
    };
    if let Err(e) = cli.common.resolve() {
        eprintln!("Error: {e}");
        return ExitCode::from(1);
    }
    // The daemon keeps programs of either format resident and tells them
    // apart itself; only a command that runs here looks at the format.
    #[cfg(unix)]
    if let Some(code) = daemon::forward(&cli) {
        return ExitCode::from(code);
    }
    match run(cli, t_start) {
        Ok(code) => ExitCode::from(code),
        Err(e) => {
            eprintln!("Error: {e}");
            ExitCode::from(1)
        }
    }
}

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

    #[test]
    fn dex_names_sort_by_number_then_name() {
        let mut names = vec!["classes10.dex", "extra.dex", "classes2.dex", "classes.dex", "classes02.dex", "classesX.dex"];
        names.sort_by(|a, b| dex_rank(a).cmp(&dex_rank(b)));
        assert_eq!(names, ["classes.dex", "classes2.dex", "classes10.dex", "classes02.dex", "classesX.dex", "extra.dex"]);
    }

    #[test]
    fn dex_order_holds_entries_until_earlier_ones_are_complete() {
        let mut order = DexOrder { order: vec!["classes.dex".into(), "classes2.dex".into()], next: 0, parts: 2, pending: HashMap::new() };
        assert!(order.push("classes2.dex", 1, "2b").is_empty());
        assert!(order.push("classes.dex", 1, "1b").is_empty(), "classes.dex still misses a part");
        assert_eq!(order.push("classes.dex", 0, "1a"), ["1a", "1b"]);
        assert!(order.push("extra.dex", 0, "x").is_empty());
        // A part that never came (a cancelled run) is released at the end, in order.
        assert_eq!(order.finish(), ["2b", "x"]);
    }
}