mldsa-native-rs 0.0.1-alpha.6

FFI bindings and optional wrapper for the mldsa-native ML-DSA implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
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
#!/usr/bin/env python3
# Copyright (c) The mldsa-native project authors
# Copyright (c) The mlkem-native project authors
# SPDX-License-Identifier: Apache-2.0 OR ISC OR MIT

"""Convenience CLI script wrapping various `make` invocations for
building and running tests and benchmarks.

See the command line interface for more information."""

import platform
import argparse
import os
import re
import sys
import time
import logging
import subprocess
import json

from enum import Enum
from functools import reduce

#
# Some utility functions
#


def dict2str(dict):
    s = ""
    for k, v in dict.items():
        s += f"{k}={v} "
    return s


def github_log(msg):
    if os.environ.get("GITHUB_ENV") is None:
        return
    print(msg)


def github_summary(title, test_label, results):
    """Generate summary for GitHub CI"""
    summary_file = os.environ.get("GITHUB_STEP_SUMMARY")

    res = list(results.values())

    if isinstance(results[SCHEME.MLDSA44], str):
        summaries = list(
            map(
                lambda s: f" {s} |",
                reduce(
                    lambda acc, s: [
                        line1 + " | " + line2 for line1, line2 in zip(acc, s)
                    ],
                    [s.splitlines() for s in res],
                ),
            )
        )
        summaries = [f"| {test_label} |" + summaries[0]] + [
            "| |" + x for x in summaries[1:]
        ]
    else:
        summaries = [
            reduce(
                lambda acc, b: f"{acc} " + (":x: |" if b else ":white_check_mark: |"),
                res,
                f"| {test_label} |",
            )
        ]

    def find_last_consecutive_match(lines, s):
        for i, v in enumerate(lines[s + 1 :]):
            if not v.startswith("|") or not v.endswith("|"):
                return i + 1
        return len(lines)

    def add_summaries(fn, title, summaries):
        summary_title = "| Tests |"
        summary_table_format = "| ----- |"
        for s in SCHEME:
            summary_title += f" {s} |"
            summary_table_format += " ----- |"

        with open(fn, "r") as f:
            pre_summaries = [x for x in f.read().splitlines() if x]
            if title in pre_summaries:
                if summary_title not in pre_summaries:
                    summaries = [summary_title, summary_table_format] + summaries
                    pre_summaries = (
                        pre_summaries[: pre_summaries.index(title) + 1]
                        + summaries
                        + pre_summaries[pre_summaries.index(title) + 1 :]
                    )
                else:
                    i = find_last_consecutive_match(
                        pre_summaries, pre_summaries.index(title)
                    )
                    pre_summaries = pre_summaries[:i] + summaries + pre_summaries[i:]
                return ("w", pre_summaries)
            else:
                pre_summaries = [
                    title,
                    summary_title,
                    summary_table_format,
                ] + summaries
                return ("a", pre_summaries)

    if summary_file is not None:
        (access_mode, summaries) = add_summaries(summary_file, title, summaries)
        with open(summary_file, access_mode) as f:
            print("\n".join(summaries), file=f)


logging.basicConfig(
    stream=sys.stdout, format="%(levelname)-5s > %(name)-40s %(message)s"
)


def config_logger(verbose):
    logger = logging.getLogger()

    if verbose:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)


def logger(test_type, scheme, cross_prefix, opt):
    """Emit line indicating the processing of the given test"""

    test_desc = str(test_type)

    compile_mode = "cross" if cross_prefix else "native"
    if opt is None:
        opt_label = ""
    elif opt is True:
        opt_label = " opt"
    else:
        opt_label = " no_opt"

    if isinstance(test_type, TEST_TYPES) and test_type.is_example():
        sz = 40
    else:
        sz = 18

    return logging.getLogger(
        "{0:<{1}} {2:<11} {3:<17}".format(
            test_desc,
            sz,
            str(scheme),
            "({}{}):".format(compile_mode, opt_label),
        )
    )


#
# Core classes providing a wrapper around invocations to `make`
# for building and running tests and benchmarks
#


class SCHEME(Enum):
    MLDSA44 = 1
    MLDSA65 = 2
    MLDSA87 = 3

    def __str__(self):
        if self == SCHEME.MLDSA44:
            return "ML-DSA-44"
        if self == SCHEME.MLDSA65:
            return "ML-DSA-65"
        if self == SCHEME.MLDSA87:
            return "ML-DSA-87"

    def suffix(self):
        if self == SCHEME.MLDSA44:
            return "44"
        if self == SCHEME.MLDSA65:
            return "65"
        if self == SCHEME.MLDSA87:
            return "87"

    def from_mode(mode):
        if isinstance(mode, str):
            mode = int(mode)
        if mode == 44:
            return SCHEME.MLDSA44
        if mode == 65:
            return SCHEME.MLDSA65
        if mode == 87:
            return SCHEME.MLDSA87


class TEST_TYPES(Enum):
    FUNC = 1
    BENCH = 2
    KAT = 3
    BENCH_COMPONENTS = 4
    ACVP = 5
    BRING_YOUR_OWN_FIPS202 = 6
    BRING_YOUR_OWN_FIPS202_STATIC = 7
    CUSTOM_BACKEND = 8
    BASIC = 9
    MONOLITHIC_BUILD = 10
    MONOLITHIC_BUILD_MULTILEVEL = 11
    MULTILEVEL_BUILD = 12
    MULTILEVEL_BUILD_NATIVE = 13
    MONOLITHIC_BUILD_MULTILEVEL_NATIVE = 14
    MONOLITHIC_BUILD_NATIVE = 15
    STACK = 16
    SIZE = 17
    BASIC_DETERMINISTIC = 18
    UNIT = 19
    ALLOC = 20
    BASIC_LOWRAM = 21
    RNG_FAIL = 22
    WYCHEPROOF = 23
    ABICHECK = 24

    def is_benchmark(self):
        return self in [TEST_TYPES.BENCH, TEST_TYPES.BENCH_COMPONENTS]

    def is_example(self):
        return self in TEST_TYPES.examples()

    @staticmethod
    def examples():
        return [
            TEST_TYPES.BRING_YOUR_OWN_FIPS202,
            TEST_TYPES.BRING_YOUR_OWN_FIPS202_STATIC,
            TEST_TYPES.CUSTOM_BACKEND,
            TEST_TYPES.BASIC,
            TEST_TYPES.MONOLITHIC_BUILD,
            TEST_TYPES.MONOLITHIC_BUILD_NATIVE,
            TEST_TYPES.MONOLITHIC_BUILD_MULTILEVEL,
            TEST_TYPES.MONOLITHIC_BUILD_MULTILEVEL_NATIVE,
            TEST_TYPES.MULTILEVEL_BUILD,
            TEST_TYPES.MULTILEVEL_BUILD_NATIVE,
            TEST_TYPES.BASIC_DETERMINISTIC,
            TEST_TYPES.BASIC_LOWRAM,
        ]

    @staticmethod
    def from_string(s):
        for e in TEST_TYPES.examples():
            if str.lower(e.name) == str.lower(s):
                return e
        raise Exception(
            f"Could not find example {s}. Examples: {list(map(lambda e: str.lower(e.name), TEST_TYPES.examples()))}"
        )

    def __str__(self):
        return self.desc()

    def desc(self):
        if self == TEST_TYPES.FUNC:
            return "Functional Test"
        if self == TEST_TYPES.BENCH:
            return "Benchmark"
        if self == TEST_TYPES.BENCH_COMPONENTS:
            return "Benchmark Components"
        if self == TEST_TYPES.KAT:
            return "Kat Test"
        if self == TEST_TYPES.ACVP:
            return "ACVP Test"
        if self == TEST_TYPES.WYCHEPROOF:
            return "Wycheproof Test"
        if self == TEST_TYPES.STACK:
            return "Stack Usage Test"
        if self == TEST_TYPES.BRING_YOUR_OWN_FIPS202:
            return "Example (Bring-Your-Own-FIPS202)"
        if self == TEST_TYPES.BRING_YOUR_OWN_FIPS202_STATIC:
            return "Example (Bring-Your-Own-FIPS202, static)"
        if self == TEST_TYPES.CUSTOM_BACKEND:
            return "Example (Custom Backend)"
        if self == TEST_TYPES.BASIC:
            return "Example (mldsa-native as code package)"
        if self == TEST_TYPES.BASIC_DETERMINISTIC:
            return "Example (mldsa-native as code package without randombytes() implementation)"
        if self == TEST_TYPES.BASIC_LOWRAM:
            return "Example (mldsa-native with reduced RAM usage)"
        if self == TEST_TYPES.MONOLITHIC_BUILD:
            return "Example (monobuild)"
        if self == TEST_TYPES.MONOLITHIC_BUILD_NATIVE:
            return "Example (monobuild, native)"
        if self == TEST_TYPES.MONOLITHIC_BUILD_MULTILEVEL:
            return "Example (monobuild, multilevel)"
        if self == TEST_TYPES.MONOLITHIC_BUILD_MULTILEVEL_NATIVE:
            return "Example (monobuild, multilevel, native)"
        if self == TEST_TYPES.MULTILEVEL_BUILD:
            return "Example (multilevel build)"
        if self == TEST_TYPES.MULTILEVEL_BUILD_NATIVE:
            return "Example (multilevel build, native)"
        if self == TEST_TYPES.SIZE:
            return "Measurement Code Size"
        if self == TEST_TYPES.UNIT:
            return "Unit Test"
        if self == TEST_TYPES.ALLOC:
            return "Alloc Test"
        if self == TEST_TYPES.RNG_FAIL:
            return "RNG Failure Test"
        if self == TEST_TYPES.ABICHECK:
            return "ABI Compliance Test"

    def make_dir(self):
        if self == TEST_TYPES.BRING_YOUR_OWN_FIPS202:
            return "examples/bring_your_own_fips202"
        if self == TEST_TYPES.BRING_YOUR_OWN_FIPS202_STATIC:
            return "examples/bring_your_own_fips202_static"
        if self == TEST_TYPES.CUSTOM_BACKEND:
            return "examples/custom_backend"
        if self == TEST_TYPES.BASIC:
            return "examples/basic"
        if self == TEST_TYPES.BASIC_DETERMINISTIC:
            return "examples/basic_deterministic"
        if self == TEST_TYPES.BASIC_LOWRAM:
            return "examples/basic_lowram"
        if self == TEST_TYPES.MONOLITHIC_BUILD:
            return "examples/monolithic_build"
        if self == TEST_TYPES.MONOLITHIC_BUILD_NATIVE:
            return "examples/monolithic_build_native"
        if self == TEST_TYPES.MONOLITHIC_BUILD_MULTILEVEL:
            return "examples/monolithic_build_multilevel"
        if self == TEST_TYPES.MONOLITHIC_BUILD_MULTILEVEL_NATIVE:
            return "examples/monolithic_build_multilevel_native"
        if self == TEST_TYPES.MULTILEVEL_BUILD:
            return "examples/multilevel_build"
        if self == TEST_TYPES.MULTILEVEL_BUILD_NATIVE:
            return "examples/multilevel_build_native"
        return ""

    def make_target(self):
        if self == TEST_TYPES.FUNC:
            return "func"
        if self == TEST_TYPES.BENCH:
            return "bench"
        if self == TEST_TYPES.BENCH_COMPONENTS:
            return "bench_components"
        if self == TEST_TYPES.KAT:
            return "kat"
        if self == TEST_TYPES.ACVP:
            return "acvp"
        if self == TEST_TYPES.WYCHEPROOF:
            return "wycheproof"
        if self == TEST_TYPES.STACK:
            return "stack"
        if self == TEST_TYPES.BRING_YOUR_OWN_FIPS202:
            return ""
        if self == TEST_TYPES.BRING_YOUR_OWN_FIPS202_STATIC:
            return ""
        if self == TEST_TYPES.CUSTOM_BACKEND:
            return ""
        if self == TEST_TYPES.BASIC:
            return ""
        if self == TEST_TYPES.BASIC_DETERMINISTIC:
            return ""
        if self == TEST_TYPES.BASIC_LOWRAM:
            return ""
        if self == TEST_TYPES.MONOLITHIC_BUILD:
            return ""
        if self == TEST_TYPES.MONOLITHIC_BUILD_NATIVE:
            return ""
        if self == TEST_TYPES.MONOLITHIC_BUILD_MULTILEVEL:
            return ""
        if self == TEST_TYPES.MONOLITHIC_BUILD_MULTILEVEL_NATIVE:
            return ""
        if self == TEST_TYPES.MULTILEVEL_BUILD:
            return ""
        if self == TEST_TYPES.MULTILEVEL_BUILD_NATIVE:
            return ""
        if self == TEST_TYPES.SIZE:
            return "size"
        if self == TEST_TYPES.UNIT:
            return "unit"
        if self == TEST_TYPES.ALLOC:
            return "alloc"
        if self == TEST_TYPES.RNG_FAIL:
            return "rng_fail"
        if self == TEST_TYPES.ABICHECK:
            return "abicheck"

    def make_run_target(self, scheme):
        t = self.make_target()
        if t == "":
            run_t = "run"
        else:
            run_t = f"run_{t}"
        if scheme is not None:
            return f"{run_t}_{scheme.suffix()}"
        else:
            return run_t


class Tests:
    def __init__(self, args):
        config_logger(args.verbose)
        self.args = args
        self.failed = []

    def fail(self, info):
        self.failed.append(info)

    def check_fail(self):
        num_failed = len(self.failed)
        if num_failed > 0:
            print(f"{num_failed} tests FAILED")
            for info in self.failed:
                print(f"* {info}")
            exit(1)
        print("All good!")
        exit(0)

    def cmd_prefix(self):
        res = []
        if self.args.run_as_root is True:
            res += ["sudo"]
        if self.args.exec_wrapper is not None and self.args.exec_wrapper != "":
            res += self.args.exec_wrapper.split(" ")
        if self.args.mac_taskpolicy is not None:
            res += ["taskpolicy", "-c", f"{self.args.mac_taskpolicy}"]

        return res

    def make_j(self):
        if self.args.j is None or int(self.args.j) == 1:
            return []
        return [f"-j{self.args.j}"]

    def do_opt_all(self):
        return self.args.opt.lower() == "all"

    def do_opt(self):
        return self.args.opt.lower() in ["all", "opt"]

    def do_no_opt(self):
        return self.args.opt.lower() in ["all", "no_opt"]

    def compile_mode(self):
        return "Cross" if self.args.cross_prefix != "" else "Native"

    def _compile_schemes(self, test_type, opt):
        """compile or cross compile with some extra environment variables and makefile arguments"""

        if opt is None:
            opt_label = ""
        elif opt is True:
            opt_label = " opt"
        else:
            opt_label = " no_opt"

        github_log(
            f"::group::compile {self.compile_mode()}{opt_label} {test_type.desc()}"
        )

        log = logger(test_type, "Compile", self.args.cross_prefix, opt)

        extra_make_args = []
        # Those options are not used in the examples
        if test_type.is_example() is False:
            extra_make_args += [f"OPT={int(opt)}", f"AUTO={int(self.args.auto)}"]
        if test_type.is_benchmark() is True:
            extra_make_args += [f"CYCLES={self.args.cycles}"]
        if test_type.make_dir() != "":
            extra_make_args += ["-C", test_type.make_dir()]
        extra_make_args += self.make_j()

        target = test_type.make_target()
        target = [target] if target != "" else []
        args = ["make"] + target + extra_make_args

        # Force static compilation for cross builds
        cflags = self.args.cflags
        if cflags is None:
            cflags = ""
        ldflags = self.args.ldflags
        if ldflags is None:
            ldflags = ""

        if test_type.is_example() and self.args.cross_prefix != "":
            cflags += " -static"

        # Add FIPS202 backend selection if specified and this is an OPT build
        if self.args.fips202_aarch64_backend != "auto" and opt is True:
            # Make sure we're forcing AArch64 architecture
            if " -DMLD_FORCE_AARCH64" not in cflags:
                cflags += " -DMLD_FORCE_AARCH64"

            # Enable native backend for FIPS202
            cflags += " -DMLD_CONFIG_USE_NATIVE_BACKEND_FIPS202"

            # Specify the backend file
            cflags += f' -DMLD_CONFIG_FIPS202_BACKEND_FILE=\\"fips202/native/aarch64/{self.args.fips202_aarch64_backend}.h\\"'

        env_update = {}
        if cflags != "":
            env_update["CFLAGS"] = cflags
        if ldflags != "":
            env_update["LDFLAGS"] = ldflags
        if self.args.cross_prefix != "":
            env_update["CROSS_PREFIX"] = self.args.cross_prefix

        env = os.environ.copy()
        env.update(env_update)

        log.info(dict2str(env_update) + " ".join(args))

        p = subprocess.run(
            args,
            stdout=subprocess.DEVNULL if not self.args.verbose else None,
            env=env,
        )

        if p.returncode != 0:
            log.error(f"make failed: {p.returncode}")
            self.fail(f"Compilation for ({test_type}{opt_label})")

        github_log("::endgroup::")

    def _run_scheme(
        self,
        test_type,
        opt,
        scheme,
        suppress_output=True,
    ):
        """Run the binary in all different ways

        Arguments:

        - scheme: Scheme to test
        - suppress_output: Indicate whether to suppress or print-and-return the output
        """

        if opt is None:
            opt_label = ""
        elif opt is True:
            opt_label = " opt"
        else:
            opt_label = " no_opt"

        if scheme is None:
            scheme_str = "All"
        else:
            scheme_str = str(scheme)

        log = logger(test_type, scheme_str, self.args.cross_prefix, opt)

        args = ["make", test_type.make_run_target(scheme)]
        if test_type.is_benchmark() is False and test_type.is_example() is False:
            args += self.make_j()
        if test_type.make_dir() != "":
            args += ["-C", test_type.make_dir()]

        env_update = {}
        if len(self.cmd_prefix()) > 0:
            env_update["EXEC_WRAPPER"] = " ".join(self.cmd_prefix())

        # Add stack analysis flags for stack tests
        if test_type == TEST_TYPES.STACK:
            stack_flags = []
            if hasattr(self.args, "peak_only") and self.args.peak_only:
                stack_flags.append("--peak-only")
            if hasattr(self.args, "dump_massif") and self.args.dump_massif:
                stack_flags.append("--dump-massif")
            if stack_flags:
                env_update["STACK_ANALYSIS_FLAGS"] = " ".join(stack_flags)

        # Add ACVP version for ACVP tests
        if test_type == TEST_TYPES.ACVP and hasattr(self.args, "version"):
            env_update["ACVP_VERSION"] = self.args.version

        env = os.environ.copy()
        env.update(env_update)

        cmd_str = dict2str(env_update) + " ".join(args)
        log.info(cmd_str)

        p = subprocess.run(args, capture_output=True, universal_newlines=False, env=env)

        if p.returncode != 0:
            log.error(f"'{cmd_str}' failed with with {p.returncode}")
            log.error(p.stderr.decode())
            self.fail(f"{test_type.desc()} ({scheme_str}{opt_label})")
            return True  # Failure
        elif suppress_output is True:
            if self.args.verbose is True:
                log.info(p.stdout.decode())
            return False  # No failure
        else:
            result = p.stdout.decode()
            log.info(result)
            return result

    def _run_schemes(self, test_type, opt, suppress_output=True):
        """Arguments:

        - opt: Whether native backends should be enabled
        - suppress_output: Indicate whether to suppress or print-and-return the output
        """

        results = {}

        k = "opt" if opt else "no_opt"

        github_log(f"::group::run {self.compile_mode()} {k} {test_type.desc()}")

        results[k] = {}
        for scheme in SCHEME:
            result = self._run_scheme(
                test_type,
                opt,
                scheme,
                suppress_output,
            )

            results[k][scheme] = result

        title = "## " + (self.compile_mode()) + " " + (k.capitalize()) + " Tests"
        github_summary(title, test_type.desc(), results[k])

        github_log("::endgroup::")

        if suppress_output is True:
            # In this case, we only gather success/failure booleans
            return reduce(
                lambda acc, c: acc or c,
                [r for rs in results.values() for r in rs.values()],
                False,
            )
        else:
            return results

    def func(self):
        def _func(opt):
            self._compile_schemes(TEST_TYPES.FUNC, opt)
            if self.args.check_namespace is True:
                p = subprocess.run(
                    ["python3", "check-namespace"],
                    stdout=subprocess.DEVNULL if not self.args.verbose else None,
                    cwd="scripts",
                )
                if p.returncode != 0:
                    self.fail(f"Namespacing failed for opt={opt}")
            if self.args.run:
                self._run_schemes(TEST_TYPES.FUNC, opt)

        if self.do_no_opt():
            _func(False)
        if self.do_opt():
            _func(True)

        self.check_fail()

    def kat(self):
        def _kat(opt):
            self._compile_schemes(TEST_TYPES.KAT, opt)
            if self.args.run:
                self._run_schemes(TEST_TYPES.KAT, opt)

        if self.do_no_opt():
            _kat(False)
        if self.do_opt():
            _kat(True)

        self.check_fail()

    def unit(self):
        def _unit(opt):
            self._compile_schemes(TEST_TYPES.UNIT, opt)
            if self.args.run:
                self._run_schemes(TEST_TYPES.UNIT, opt)

        if self.do_no_opt():
            _unit(False)
        if self.do_opt():
            _unit(True)

        self.check_fail()

    def alloc(self):
        def _alloc(opt):
            self._compile_schemes(TEST_TYPES.ALLOC, opt)
            if self.args.run:
                self._run_schemes(TEST_TYPES.ALLOC, opt)

        if self.do_no_opt():
            _alloc(False)
        if self.do_opt():
            _alloc(True)

        self.check_fail()

    def rng_fail(self):
        def _rng_fail(opt):
            self._compile_schemes(TEST_TYPES.RNG_FAIL, opt)
            if self.args.run:
                self._run_schemes(TEST_TYPES.RNG_FAIL, opt)

        if self.do_no_opt():
            _rng_fail(False)
        if self.do_opt():
            _rng_fail(True)

        self.check_fail()

    def abicheck(self):
        """Run ABI compliance tests for assembly functions."""
        if not self.do_opt():
            return

        self._compile_schemes(TEST_TYPES.ABICHECK, True)
        if self.args.run:
            self._run_scheme(TEST_TYPES.ABICHECK, True, None)

        self.check_fail()

    def acvp(self):
        def _acvp(opt):
            self._compile_schemes(TEST_TYPES.ACVP, opt)
            if self.args.run:
                self._run_scheme(TEST_TYPES.ACVP, opt, None)

        if self.do_no_opt():
            _acvp(False)
        if self.do_opt():
            _acvp(True)

        self.check_fail()

    def wycheproof(self):
        def _wycheproof(opt):
            self._compile_schemes(TEST_TYPES.WYCHEPROOF, opt)
            if self.args.run:
                self._run_scheme(TEST_TYPES.WYCHEPROOF, opt, None)

        if self.do_no_opt():
            _wycheproof(False)
        if self.do_opt():
            _wycheproof(True)

        self.check_fail()

    def examples(self):
        if self.args.l is None:
            items = TEST_TYPES.examples()
        else:
            items = list(map(TEST_TYPES.from_string, self.args.l))

        # Filter out excluded examples
        if hasattr(self.args, "exclude_example") and self.args.exclude_example:
            excluded = [TEST_TYPES.from_string(ex) for ex in self.args.exclude_example]
            items = [e for e in items if e not in excluded]

        for e in items:
            self._compile_schemes(e, None)
            self._run_scheme(e, None, None)

    def bench(self):
        output = self.args.output
        components = self.args.components

        if components is False:
            test_type = TEST_TYPES.BENCH
        else:
            test_type = TEST_TYPES.BENCH_COMPONENTS
            output = False

        # NOTE: We haven't yet decided how to output both opt/no-opt benchmark results
        resultss = None
        if self.do_opt_all():
            self._compile_schemes(test_type, False)
            if self.args.run:
                self._run_schemes(test_type, False, suppress_output=False)
            self._compile_schemes(test_type, True)
            if self.args.run:
                resultss = self._run_schemes(test_type, True, suppress_output=False)
        else:
            self._compile_schemes(test_type, self.do_opt())
            if self.args.run:
                resultss = self._run_schemes(
                    test_type, self.do_opt(), suppress_output=False
                )

        if resultss is None:
            self.check_fail()

        # NOTE: There will only be one items in resultss, as we haven't yet decided how to write both opt/no-opt benchmark results
        for k, results in resultss.items():
            if not (results is not None and output is not None and components is False):
                continue

            v = []
            for scheme in results:
                schemeStr = str(scheme)
                r = results[scheme]

                # The first 3 lines of the output are expected to be
                # keypair cycles=X
                # sign cycles=X
                # verify cycles=X

                lines = [line for line in r.splitlines() if "=" in line]

                d = {k.strip(): int(v) for k, v in (ln.split("=") for ln in lines)}
                for primitive in ["keypair", "sign", "verify"]:
                    v.append(
                        {
                            "name": f"{schemeStr} {primitive}",
                            "unit": "cycles",
                            "value": d[f"{primitive} cycles (avg)"],
                        }
                    )

            with open(output, "w") as f:
                f.write(json.dumps(v))

        self.check_fail()

    def stack(self):
        """Stack usage analysis"""

        def _stack(opt):
            self._compile_schemes(TEST_TYPES.STACK, opt)
            if self.args.run:
                self._run_schemes(TEST_TYPES.STACK, opt, suppress_output=False)

        if self.do_no_opt():
            _stack(False)
        if self.do_opt():
            _stack(True)

        self.check_fail()

    def size(self):
        test_type = TEST_TYPES.SIZE

        resultss = None

        if self.do_opt_all():
            self._compile_schemes(test_type, False)
            if self.args.run:
                self._run_schemes(test_type, False, suppress_output=False)
            self._compile_schemes(test_type, True)
            if self.args.run:
                resultss = self._run_schemes(test_type, True, suppress_output=False)
        else:
            self._compile_schemes(test_type, self.do_opt())
            if self.args.run:
                resultss = self._run_schemes(
                    test_type, self.do_opt(), suppress_output=False
                )

        if resultss is None:
            self.check_fail()

    def all(self):
        func = self.args.func
        kat = self.args.kat
        acvp = self.args.acvp
        wycheproof = self.args.wycheproof
        examples = self.args.examples
        stack = self.args.stack
        unit = self.args.unit
        alloc = self.args.alloc
        rng_fail = self.args.rng_fail
        abicheck = self.args.abicheck

        def _all(opt):
            if func is True:
                self._compile_schemes(TEST_TYPES.FUNC, opt)
            if kat is True:
                self._compile_schemes(TEST_TYPES.KAT, opt)
            if acvp is True:
                self._compile_schemes(TEST_TYPES.ACVP, opt)
            if wycheproof is True:
                self._compile_schemes(TEST_TYPES.WYCHEPROOF, opt)
            if stack is True:
                self._compile_schemes(TEST_TYPES.STACK, opt)
            if unit is True:
                self._compile_schemes(TEST_TYPES.UNIT, opt)
            if alloc is True:
                self._compile_schemes(TEST_TYPES.ALLOC, opt)
            if rng_fail is True:
                self._compile_schemes(TEST_TYPES.RNG_FAIL, opt)
            if abicheck is True and opt:
                self._compile_schemes(TEST_TYPES.ABICHECK, opt)

            if self.args.check_namespace is True:
                p = subprocess.run(
                    ["python3", "check-namespace"],
                    stdout=subprocess.DEVNULL if not self.args.verbose else None,
                    cwd="scripts",
                )
                if p.returncode != 0:
                    self.fail(f"Namespacing failed for opt={opt}")

            if self.args.run is False:
                return

            if func is True:
                self._run_schemes(TEST_TYPES.FUNC, opt)
            if kat is True:
                self._run_schemes(TEST_TYPES.KAT, opt)
            if acvp is True:
                self._run_scheme(TEST_TYPES.ACVP, opt, None)
            if wycheproof is True:
                self._run_scheme(TEST_TYPES.WYCHEPROOF, opt, None)
            if stack is True:
                self._run_schemes(TEST_TYPES.STACK, opt, suppress_output=False)
            if unit is True:
                self._run_schemes(TEST_TYPES.UNIT, opt)
            if alloc is True:
                self._run_schemes(TEST_TYPES.ALLOC, opt)
            if rng_fail is True:
                self._run_schemes(TEST_TYPES.RNG_FAIL, opt)
            if abicheck is True and opt:
                self._run_scheme(TEST_TYPES.ABICHECK, opt, None)

        if self.do_no_opt():
            _all(False)
        if self.do_opt():
            _all(True)

        if examples is True:
            self.examples()

        self.check_fail()

    def cbmc(self):
        def list_proofs():
            cmd_str = ["./proofs/cbmc/list_proofs.sh"]
            p = subprocess.run(cmd_str, capture_output=True, universal_newlines=False)
            proofs = filter(lambda s: s.strip() != "", p.stdout.decode().split("\n"))
            return list(proofs)

        if self.args.list_functions:
            for p in list_proofs():
                print(p)
            exit(0)

        def run_cbmc_single_step(mldsa_parameter_set, proofs):
            envvars = {"MLD_CONFIG_PARAMETER_SET": mldsa_parameter_set}
            if self.args.reduce_ram:
                envvars["MLD_CONFIG_REDUCE_RAM"] = "1"
            scheme = SCHEME.from_mode(mldsa_parameter_set)
            num_proofs = len(proofs)
            for i, func in enumerate(proofs):
                log = logger(f"CBMC ({i + 1}/{num_proofs})", scheme, None, None)
                log.info(f"Starting CBMC proof for {func}")
                start = time.time()
                try:
                    p = subprocess.run(
                        [
                            "python3",
                            "run-cbmc-proofs.py",
                            "--summarize",
                            "--no-coverage",
                            "--per-proof-timeout",
                            str(self.args.per_proof_timeout),
                            "-p",
                            func,
                        ]
                        + self.make_j(),
                        cwd="proofs/cbmc",
                        env=os.environ.copy() | envvars,
                        timeout=self.args.timeout,
                        capture_output=(self.args.verbose is False),
                    )
                except subprocess.TimeoutExpired as e:
                    log.error(f"   TIMEOUT (after {self.args.timeout}s)")
                    log.error(e.stderr.decode())
                    self.fail(f"CBMC proof for {func}")
                    if self.args.fail_upon_error:
                        log.error(
                            "Aborting proofs, as requested by -f/--fail-upon-error"
                        )
                        exit(1)
                    continue

                end = time.time()
                dur = int(end - start)
                if p.returncode != 0:
                    log.error(f"   FAILED (after {dur}s)")
                    if p.stderr is not None:
                        log.error(p.stderr.decode())
                    self.fail(f"CBMC proof for {func}")
                else:
                    log.info(f"   SUCCESS (after {dur}s)")

        def run_cbmc(mldsa_parameter_set):
            log = logger("CBMC", SCHEME.from_mode(mldsa_parameter_set), None, None)
            all_proofs = list_proofs()
            proofs = all_proofs
            if self.args.start_with is not None:
                try:
                    idx = proofs.index(self.args.start_with)
                    proofs = proofs[idx:]
                except ValueError:
                    log.error(
                        f"Could not find function {self.args.start_with}. Running all proofs"
                    )
            if self.args.proof is not None:
                proofs = []
                for pat in self.args.proof:
                    # Replace wildcards by regexp wildcards
                    pat = pat.replace("*", ".*")
                    proofs += list(filter(lambda x: re.match(pat, x), all_proofs))
                proofs = sorted(set(proofs))

            if self.args.single_step:
                run_cbmc_single_step(mldsa_parameter_set, proofs)
                return
            envvars = {"MLD_CONFIG_PARAMETER_SET": mldsa_parameter_set}
            if self.args.reduce_ram:
                envvars["MLD_CONFIG_REDUCE_RAM"] = "1"
            cmd = (
                [
                    "python3",
                    "run-cbmc-proofs.py",
                    "--summarize",
                    "--no-coverage",
                    "--per-proof-timeout",
                    str(self.args.per_proof_timeout),
                    "-p",
                ]
                + proofs
                + self.make_j()
            )
            if self.args.output_result_json:
                cmd.extend(["--output-result-json", self.args.output_result_json])
            p = subprocess.run(
                cmd,
                cwd="proofs/cbmc",
                env=os.environ.copy() | envvars,
            )

            if p.returncode != 0:
                self.fail(f"CBMC proofs for parameter set={mldsa_parameter_set}")

        mldsa_parameter_set = self.args.mldsa_parameter_set
        if mldsa_parameter_set == "ALL":
            run_cbmc("44")
            run_cbmc("65")
            run_cbmc("87")
        else:
            run_cbmc(mldsa_parameter_set)

        self.check_fail()

    def hol_light(self):
        machine = platform.machine().lower()
        if machine in ["arm64", "aarch64"]:
            arch = "aarch64"
        elif machine in ["x86_64"]:
            arch = "x86_64"
        else:
            self.fail(f"HOL-Light unsupported architecture: {machine}")
            self.check_fail()

        def list_proofs(arch):
            cmd_str = ["./proofs/hol_light/" + arch + "/list_proofs.sh"]
            p = subprocess.run(cmd_str, capture_output=True, universal_newlines=False)
            proofs = filter(lambda s: s.strip() != "", p.stdout.decode().split("\n"))
            return list(proofs)

        if self.args.list_functions:
            for p in list_proofs(arch):
                print(p)
            exit(0)

        def run_hol_light_single_step(proofs, arch):
            num_proofs = len(proofs)
            for i, func in enumerate(proofs):
                log = logger(f"HOL_LIGHT ({i + 1}/{num_proofs})", None, None, None)
                log.info(f"Starting HOL-Light proof for {func}")
                start = time.time()
                proof_bin = f"mldsa/{func}.native"
                proof_target = f"mldsa/{func}.correct"
                proof_dir = "proofs/hol_light/" + arch
                # Remove intermediate proof files to force-rerun
                try:
                    os.remove(os.path.join(proof_dir, proof_bin))
                    os.remove(os.path.join(proof_dir, proof_target))
                except FileNotFoundError:
                    pass
                p = subprocess.run(
                    [
                        "make",
                        f"mldsa/{func}.correct",
                    ]
                    + self.make_j(),
                    cwd="proofs/hol_light/" + arch,
                    env=os.environ.copy(),
                    capture_output=(self.args.verbose is False),
                )

                end = time.time()
                dur = int(end - start)
                if p.returncode != 0:
                    log.error(f"   FAILED (after {dur}s)")
                    if p.stderr is not None:
                        log.error(p.stderr.decode())
                    self.fail(f"HOL-Light proof for {func}")
                else:
                    log.info(f"   SUCCESS (after {dur}s)")

        proofs = list_proofs(arch)
        if self.args.proof is not None:
            proofs = self.args.proof

        run_hol_light_single_step(proofs, arch)
        self.check_fail()


#
# Command line interface
#


def cli():
    common_parser = argparse.ArgumentParser(add_help=False)

    # Common arguments for all sub-commands
    common_parser.add_argument(
        "-v", "--verbose", help="Show verbose output or not", action="store_true"
    )
    common_parser.add_argument(
        "-cp", "--cross-prefix", help="Cross prefix for compilation", default=""
    )
    common_parser.add_argument(
        "--cflags", help="Extra cflags to passed in (e.g. '-mcpu=cortex-a72')"
    )
    common_parser.add_argument(
        "--ldflags", help="Extra ldflags to passed in (e.g. '-static')"
    )
    common_parser.add_argument(
        "-j",
        help="Number of jobs to be used for `make` invocations",
        default=os.cpu_count(),
    )

    # --auto / --no-auto
    auto_group = common_parser.add_mutually_exclusive_group()
    auto_group.add_argument(
        "--auto",
        action="store_true",
        dest="auto",
        help="Allow makefile to auto configure system specific preprocessor",
        default=True,
    )
    auto_group.add_argument(
        "--no-auto",
        action="store_false",
        dest="auto",
        help="Disallow makefile to auto configure system specific preprocessor",
    )

    common_parser.add_argument(
        "--opt",
        help="Determine whether to compile/run the opt/no_opt binary or both",
        choices=["ALL", "OPT", "NO_OPT"],
        type=str.upper,
        default="ALL",
    )

    common_parser.add_argument(
        "--fips202-aarch64-backend",
        help="Select FIPS202 AArch64 backend",
        choices=[
            "auto",
            "x1_scalar",
            "x1_v84a",
            "x2_v84a",
            "x4_v8a_scalar",
            "x4_v8a_v84a_scalar",
        ],
        default="auto",
        type=str,
    )

    # --run / --no-run
    run_group = common_parser.add_mutually_exclusive_group()
    run_group.add_argument(
        "--run", action="store_true", dest="run", help="Run the binaries", default=True
    )
    run_group.add_argument(
        "--no-run", action="store_false", dest="run", help="Do not run the binaries"
    )

    common_parser.add_argument(
        "-w", "--exec-wrapper", help="Run the binary with the user-customized wrapper"
    )
    common_parser.add_argument(
        "-r",
        "--run-as-root",
        default=False,
        action="store_true",
        help="Run the binary as root",
    )

    main_parser = argparse.ArgumentParser()

    cmd_subparsers = main_parser.add_subparsers(title="Commands", dest="cmd")

    # all arguments
    all_parser = cmd_subparsers.add_parser(
        "all", help="Run all tests (except benchmark for now)", parents=[common_parser]
    )

    all_parser.add_argument(
        "--check-namespace",
        help="Check namespacing of binaries",
        action="store_true",
        default=False,
    )

    func_group = all_parser.add_mutually_exclusive_group()
    func_group.add_argument(
        "--func", action="store_true", dest="func", help="Run func test", default=True
    )
    func_group.add_argument(
        "--no-func", action="store_false", dest="func", help="Do not run func test"
    )

    kat_group = all_parser.add_mutually_exclusive_group()
    kat_group.add_argument(
        "--kat", action="store_true", dest="kat", help="Run kat test", default=True
    )
    kat_group.add_argument(
        "--no-kat", action="store_false", dest="kat", help="Do not run kat test"
    )

    acvp_group = all_parser.add_mutually_exclusive_group()
    acvp_group.add_argument(
        "--acvp", action="store_true", dest="acvp", help="Run acvp test", default=True
    )
    acvp_group.add_argument(
        "--no-acvp", action="store_false", dest="acvp", help="Do not run acvp test"
    )

    wycheproof_group = all_parser.add_mutually_exclusive_group()
    wycheproof_group.add_argument(
        "--wycheproof",
        action="store_true",
        dest="wycheproof",
        help="Run wycheproof test",
        default=True,
    )
    wycheproof_group.add_argument(
        "--no-wycheproof",
        action="store_false",
        dest="wycheproof",
        help="Do not run wycheproof test",
    )

    unit_group = all_parser.add_mutually_exclusive_group()
    unit_group.add_argument(
        "--unit", action="store_true", dest="unit", help="Run unit test", default=True
    )
    unit_group.add_argument(
        "--no-unit", action="store_false", dest="unit", help="Do not run unit test"
    )

    examples_group = all_parser.add_mutually_exclusive_group()
    examples_group.add_argument(
        "--examples",
        action="store_true",
        dest="examples",
        help="Run examples",
        default=True,
    )
    examples_group.add_argument(
        "--no-examples",
        action="store_false",
        dest="examples",
        help="Do not run examples",
    )

    all_parser.add_argument(
        "--exclude-example",
        help="Exclude specific examples from running (can be used multiple times)",
        choices=[
            "bring_your_own_fips202",
            "bring_your_own_fips202_static",
            "custom_backend",
            "basic",
            "basic_deterministic",
            "basic_lowram",
            "monolithic_build",
            "monolithic_build_native",
            "monolithic_build_multilevel",
            "monolithic_build_multilevel_native",
            "multilevel_build",
            "multilevel_build_native",
        ],
        action="append",
        default=[],
    )

    stack_group = all_parser.add_mutually_exclusive_group()
    stack_group.add_argument(
        "--stack",
        action="store_true",
        dest="stack",
        help="Run stack analysis",
        default=False,
    )
    stack_group.add_argument(
        "--no-stack",
        action="store_false",
        dest="stack",
        help="Do not run stack analysis",
    )

    alloc_group = all_parser.add_mutually_exclusive_group()
    alloc_group.add_argument(
        "--alloc",
        action="store_true",
        dest="alloc",
        help="Run alloc tests",
        default=True,
    )
    alloc_group.add_argument(
        "--no-alloc",
        action="store_false",
        dest="alloc",
        help="Do not run alloc tests",
    )

    rng_fail_group = all_parser.add_mutually_exclusive_group()
    rng_fail_group.add_argument(
        "--rng-fail",
        action="store_true",
        dest="rng_fail",
        help="Run RNG failure tests",
        default=True,
    )
    rng_fail_group.add_argument(
        "--no-rng-fail",
        action="store_false",
        dest="rng_fail",
        help="Do not run RNG failure tests",
    )

    abicheck_group = all_parser.add_mutually_exclusive_group()
    abicheck_group.add_argument(
        "--abicheck",
        action="store_true",
        dest="abicheck",
        help="Run ABI compliance tests",
        default=True,
    )
    abicheck_group.add_argument(
        "--no-abicheck",
        action="store_false",
        dest="abicheck",
        help="Do not run ABI compliance tests",
    )

    # acvp arguments
    acvp_parser = cmd_subparsers.add_parser(
        "acvp", help="Run ACVP client", parents=[common_parser]
    )
    acvp_parser.add_argument(
        "--version",
        default="v1.1.0.41",
        help="ACVP test vector version (default: v1.1.0.41)",
    )

    # wycheproof arguments
    cmd_subparsers.add_parser(
        "wycheproof", help="Run Wycheproof client", parents=[common_parser]
    )

    # examples arguments
    examples_parser = cmd_subparsers.add_parser(
        "examples", help="Run examples", parents=[common_parser]
    )

    examples_parser.add_argument(
        "-l",
        help="Explicitly list the examples to run; can be called multiple times",
        choices=[
            "bring_your_own_fips202",
            "bring_your_own_fips202_static",
            "custom_backend",
            "basic",
            "basic_deterministic",
            "basic_lowram",
            "monolithic_build",
            "monolithic_build_native",
            "monolithic_build_multilevel",
            "monolithic_build_multilevel_native",
            "multilevel_build",
            "multilevel_build_native",
        ],
        action="append",
    )

    # bench arguments
    bench_parser = cmd_subparsers.add_parser(
        "bench",
        help="Run the benchmarks for all parameter sets",
        parents=[common_parser],
    )

    bench_parser.add_argument(
        "-c",
        "--cycles",
        help="Method for counting clock cycles. PMU requires (user-space) access to the Arm Performance Monitor Unit (PMU). PERF requires a kernel with perf support. MAC works on some Apple platforms, at least Apple M1.",
        choices=["NO", "PMU", "PERF", "MAC"],
        type=str.upper,
        required=True,
    )
    bench_parser.add_argument(
        "-o", "--output", help="Path to output file in json format"
    )
    if platform.system() == "Darwin":
        bench_parser.add_argument(
            "-t",
            "--mac-taskpolicy",
            help="Run the program using the specified QoS clamp. Applies to MacOS only. Setting this flag to 'background' guarantees running on E-cores. This is an abbreviation of --exec-wrapper 'taskpolicy -c {mac_taskpolicy}'.",
            choices=["utility", "background", "maintenance"],
            type=str.lower,
        )
    bench_parser.add_argument(
        "--components",
        help="Benchmark low-level components",
        action="store_true",
        default=False,
    )
    cmd_subparsers.add_parser(
        "size",
        help="Run the code size measurement for all object file",
        parents=[common_parser],
    )

    # cbmc arguments
    cbmc_parser = cmd_subparsers.add_parser(
        "cbmc",
        help="Run the CBMC proofs for all parameter sets",
        parents=[common_parser],
    )

    cbmc_parser.add_argument(
        "-kl",
        "--mldsa-parameter-set",
        help="MLDSA parameter set (MLD_CONFIG_PARAMETER_SET)",
        choices=["44", "65", "87", "ALL"],
        type=str.upper,
        default="ALL",
    )

    cbmc_parser.add_argument(
        "--single-step",
        help="Run one proof a time. This is useful for debugging",
        action="store_true",
        default=False,
    )

    cbmc_parser.add_argument(
        "--start-with",
        help="When --single-step is set, start with given proof and proceed in alphabetical order",
        default=None,
    )

    cbmc_parser.add_argument(
        "-p",
        "--proof",
        nargs="+",
        help='Space separated list of functions for which to run the CBMC proofs. Wildcard patterns "*" are allowed.',
        default=None,
    )

    cbmc_parser.add_argument(
        "--timeout",
        help="Timeout for individual CBMC proofs, in seconds",
        type=int,
        default=3600,
    )

    cbmc_parser.add_argument(
        "--per-proof-timeout",
        help="Timeout for each individual CBMC proof passed to run-cbmc-proofs.py, in seconds (default: 1800)",
        type=int,
        default=1800,
    )

    cbmc_parser.add_argument(
        "-f",
        "--fail-upon-error",
        help="Stop upon first CBMC proof failure",
        action="store_true",
        default=False,
    )

    cbmc_parser.add_argument(
        "-l",
        "--list-functions",
        help="Don't run any proofs, but list all functions for which CBMC proofs are available",
        action="store_true",
        default=False,
    )

    cbmc_parser.add_argument(
        "--output-result-json",
        help="Path to export result JSON",
        default=None,
    )

    cbmc_parser.add_argument(
        "--reduce-ram",
        help="Run CBMC proofs with MLD_CONFIG_REDUCE_RAM enabled",
        action="store_true",
        default=False,
    )

    # hol_light arguments
    hol_light_parser = cmd_subparsers.add_parser(
        "hol_light",
        help="Run the HOL_LIGHT proofs for all parameter sets",
        parents=[common_parser],
    )

    hol_light_parser.add_argument(
        "-p",
        "--proof",
        nargs="+",
        help="Space separated list of functions for which to run the HOL_LIGHT proofs.",
        default=None,
    )

    hol_light_parser.add_argument(
        "-l",
        "--list-functions",
        help="Don't run any proofs, but list all functions for which HOL_LIGHT proofs are available",
        action="store_true",
        default=False,
    )

    # func arguments
    func_parser = cmd_subparsers.add_parser(
        "func",
        help="Run the functional tests for all parameter sets",
        parents=[common_parser],
    )
    func_parser.add_argument(
        "--check-namespace",
        help="Check namespacing of binaries",
        action="store_true",
        default=False,
    )

    # kat arguments
    cmd_subparsers.add_parser(
        "kat", help="Run the kat tests for all parameter sets", parents=[common_parser]
    )

    # unit arguments
    cmd_subparsers.add_parser(
        "unit",
        help="Run the unit tests for all parameter sets",
        parents=[common_parser],
    )

    # stack arguments
    stack_parser = cmd_subparsers.add_parser(
        "stack",
        help="Analyze stack usage for all parameter sets",
        parents=[common_parser],
    )
    stack_parser.add_argument(
        "--peak-only",
        action="store_true",
        help="Show only runtime peak stack usage (skip per-function analysis)",
        default=False,
    )
    stack_parser.add_argument(
        "--dump-massif",
        action="store_true",
        help="Dump full massif log for debugging",
        default=False,
    )

    # alloc arguments
    cmd_subparsers.add_parser(
        "alloc",
        help="Run the alloc tests for all parameter sets",
        parents=[common_parser],
    )

    # rng_fail arguments
    cmd_subparsers.add_parser(
        "rng_fail",
        help="Run the RNG failure tests for all parameter sets",
        parents=[common_parser],
    )

    # abicheck arguments
    cmd_subparsers.add_parser(
        "abicheck",
        help="Run ABI compliance tests for assembly functions",
        parents=[common_parser],
    )

    args = main_parser.parse_args()

    if not hasattr(args, "mac_taskpolicy"):
        args.mac_taskpolicy = None
    if not hasattr(args, "l"):
        args.l = None

    os.chdir(os.path.join(os.path.dirname(__file__), ".."))

    if args.cmd == "all":
        Tests(args).all()
    elif args.cmd == "examples":
        Tests(args).examples()
    elif args.cmd == "acvp":
        Tests(args).acvp()
    elif args.cmd == "wycheproof":
        Tests(args).wycheproof()
    elif args.cmd == "bench":
        Tests(args).bench()
    elif args.cmd == "cbmc":
        Tests(args).cbmc()
    elif args.cmd == "hol_light":
        Tests(args).hol_light()
    elif args.cmd == "func":
        Tests(args).func()
    elif args.cmd == "kat":
        Tests(args).kat()
    elif args.cmd == "unit":
        Tests(args).unit()
    elif args.cmd == "stack":
        Tests(args).stack()
    elif args.cmd == "size":
        Tests(args).size()
    elif args.cmd == "alloc":
        Tests(args).alloc()
    elif args.cmd == "rng_fail":
        Tests(args).rng_fail()
    elif args.cmd == "abicheck":
        Tests(args).abicheck()


if __name__ == "__main__":
    cli()