aboutsummaryrefslogtreecommitdiff
blob: d149b6a0c5cd21d8863fe749f7186d101348ceba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
#ifndef Py_BUILD_CORE_MODULE
#  define Py_BUILD_CORE_MODULE
#endif

/* Always enable assertion (even in release mode) */
#undef NDEBUG

#include <Python.h>
#include "pycore_initconfig.h"    // _PyConfig_InitCompatConfig()
#include "pycore_runtime.h"       // _PyRuntime
#include "pycore_import.h"        // _PyImport_FrozenBootstrap
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>               // putenv()
#include <wchar.h>

// These functions were removed from Python 3.13 API but are still exported
// for the stable ABI. We want to test them in this program.
extern void PySys_AddWarnOption(const wchar_t *s);
extern void PySys_AddXOption(const wchar_t *s);
extern void Py_SetPath(const wchar_t *path);


int main_argc;
char **main_argv;

/*********************************************************
 * Embedded interpreter tests that need a custom exe
 *
 * Executed via Lib/test/test_embed.py
 *********************************************************/

// Use to display the usage
#define PROGRAM "test_embed"

/* Use path starting with "./" avoids a search along the PATH */
#define PROGRAM_NAME L"./_testembed"

#define INIT_LOOPS 4

// Ignore Py_DEPRECATED() compiler warnings: deprecated functions are
// tested on purpose here.
_Py_COMP_DIAG_PUSH
_Py_COMP_DIAG_IGNORE_DEPR_DECLS


static void error(const char *msg)
{
    fprintf(stderr, "ERROR: %s\n", msg);
    fflush(stderr);
}


static void config_set_string(PyConfig *config, wchar_t **config_str, const wchar_t *str)
{
    PyStatus status = PyConfig_SetString(config, config_str, str);
    if (PyStatus_Exception(status)) {
        PyConfig_Clear(config);
        Py_ExitStatusException(status);
    }
}


static void config_set_program_name(PyConfig *config)
{
    const wchar_t *program_name = PROGRAM_NAME;
    config_set_string(config, &config->program_name, program_name);
}


static void init_from_config_clear(PyConfig *config)
{
    PyStatus status = Py_InitializeFromConfig(config);
    PyConfig_Clear(config);
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }
}


static void _testembed_Py_InitializeFromConfig(void)
{
    PyConfig config;
    _PyConfig_InitCompatConfig(&config);
    config_set_program_name(&config);
    init_from_config_clear(&config);
}

static void _testembed_Py_Initialize(void)
{
   Py_SetProgramName(PROGRAM_NAME);
   Py_Initialize();
}


/*****************************************************
 * Test repeated initialisation and subinterpreters
 *****************************************************/

static void print_subinterp(void)
{
    /* Output information about the interpreter in the format
       expected in Lib/test/test_capi.py (test_subinterps). */
    PyThreadState *ts = PyThreadState_Get();
    PyInterpreterState *interp = ts->interp;
    int64_t id = PyInterpreterState_GetID(interp);
    printf("interp %" PRId64 " <0x%" PRIXPTR ">, thread state <0x%" PRIXPTR ">: ",
            id, (uintptr_t)interp, (uintptr_t)ts);
    fflush(stdout);
    PyRun_SimpleString(
        "import sys;"
        "print('id(modules) =', id(sys.modules));"
        "sys.stdout.flush()"
    );
}

static int test_repeated_init_and_subinterpreters(void)
{
    PyThreadState *mainstate, *substate;
    PyGILState_STATE gilstate;

    for (int i=1; i <= INIT_LOOPS; i++) {
        printf("--- Pass %d ---\n", i);
        _testembed_Py_InitializeFromConfig();
        mainstate = PyThreadState_Get();

        PyEval_ReleaseThread(mainstate);

        gilstate = PyGILState_Ensure();
        print_subinterp();
        PyThreadState_Swap(NULL);

        for (int j=0; j<3; j++) {
            substate = Py_NewInterpreter();
            print_subinterp();
            Py_EndInterpreter(substate);
        }

        PyThreadState_Swap(mainstate);
        print_subinterp();
        PyGILState_Release(gilstate);

        PyEval_RestoreThread(mainstate);
        Py_Finalize();
    }
    return 0;
}

#define EMBEDDED_EXT_NAME "embedded_ext"

static PyModuleDef embedded_ext = {
    PyModuleDef_HEAD_INIT,
    .m_name = EMBEDDED_EXT_NAME,
    .m_size = 0,
};

static PyObject*
PyInit_embedded_ext(void)
{
    return PyModule_Create(&embedded_ext);
}

/****************************************************************************
 * Call Py_Initialize()/Py_Finalize() multiple times and execute Python code
 ***************************************************************************/

// Used by bpo-46417 to test that structseq types used by the sys module are
// cleared properly and initialized again properly when Python is finalized
// multiple times.
static int test_repeated_init_exec(void)
{
    if (main_argc < 3) {
        fprintf(stderr, "usage: %s test_repeated_init_exec CODE\n", PROGRAM);
        exit(1);
    }
    const char *code = main_argv[2];

    for (int i=1; i <= INIT_LOOPS; i++) {
        fprintf(stderr, "--- Loop #%d ---\n", i);
        fflush(stderr);

        _testembed_Py_InitializeFromConfig();
        int err = PyRun_SimpleString(code);
        Py_Finalize();
        if (err) {
            return 1;
        }
    }
    return 0;
}

/****************************************************************************
 * Test the Py_Initialize(Ex) convenience/compatibility wrappers
 ***************************************************************************/
// This is here to help ensure there are no wrapper resource leaks (gh-96853)
static int test_repeated_simple_init(void)
{
    for (int i=1; i <= INIT_LOOPS; i++) {
        fprintf(stderr, "--- Loop #%d ---\n", i);
        fflush(stderr);

        _testembed_Py_Initialize();
        Py_Finalize();
        printf("Finalized\n"); // Give test_embed some output to check
    }
    return 0;
}


/*****************************************************
 * Test forcing a particular IO encoding
 *****************************************************/

static void check_stdio_details(const wchar_t *encoding, const wchar_t *errors)
{
    /* Output info for the test case to check */
    if (encoding) {
        printf("Expected encoding: %ls\n", encoding);
    } else {
        printf("Expected encoding: default\n");
    }
    if (errors) {
        printf("Expected errors: %ls\n", errors);
    } else {
        printf("Expected errors: default\n");
    }
    fflush(stdout);

    PyConfig config;
    _PyConfig_InitCompatConfig(&config);
    /* Force the given IO encoding */
    if (encoding) {
        config_set_string(&config, &config.stdio_encoding, encoding);
    }
    if (errors) {
        config_set_string(&config, &config.stdio_errors, errors);
    }
#ifdef MS_WINDOWS
    // gh-106659: On Windows, don't use _io._WindowsConsoleIO which always
    // announce UTF-8 for sys.stdin.encoding.
    config.legacy_windows_stdio = 1;
#endif
    config_set_program_name(&config);
    init_from_config_clear(&config);


    PyRun_SimpleString(
        "import sys;"
        "print('stdin: {0.encoding}:{0.errors}'.format(sys.stdin));"
        "print('stdout: {0.encoding}:{0.errors}'.format(sys.stdout));"
        "print('stderr: {0.encoding}:{0.errors}'.format(sys.stderr));"
        "sys.stdout.flush()"
    );
    Py_Finalize();
}

static int test_forced_io_encoding(void)
{
    /* Check various combinations */
    printf("--- Use defaults ---\n");
    check_stdio_details(NULL, NULL);
    printf("--- Set errors only ---\n");
    check_stdio_details(NULL, L"ignore");
    printf("--- Set encoding only ---\n");
    check_stdio_details(L"iso8859-1", NULL);
    printf("--- Set encoding and errors ---\n");
    check_stdio_details(L"iso8859-1", L"replace");
    return 0;
}

/*********************************************************
 * Test parts of the C-API that work before initialization
 *********************************************************/

/* The pre-initialization tests tend to break by segfaulting, so explicitly
 * flushed progress messages make the broken API easier to find when they fail.
 */
#define _Py_EMBED_PREINIT_CHECK(msg) \
    do {printf(msg); fflush(stdout);} while (0);

static int test_pre_initialization_api(void)
{
    /* the test doesn't support custom memory allocators */
    putenv("PYTHONMALLOC=");

    /* Leading "./" ensures getpath.c can still find the standard library */
    _Py_EMBED_PREINIT_CHECK("Checking Py_DecodeLocale\n");
    wchar_t *program = Py_DecodeLocale("./spam", NULL);
    if (program == NULL) {
        fprintf(stderr, "Fatal error: cannot decode program name\n");
        return 1;
    }
    _Py_EMBED_PREINIT_CHECK("Checking Py_SetProgramName\n");
    Py_SetProgramName(program);

    _Py_EMBED_PREINIT_CHECK("Initializing interpreter\n");
    Py_Initialize();
    _Py_EMBED_PREINIT_CHECK("Check sys module contents\n");
    PyRun_SimpleString("import sys; "
                       "print('sys.executable:', sys.executable)");
    _Py_EMBED_PREINIT_CHECK("Finalizing interpreter\n");
    Py_Finalize();

    _Py_EMBED_PREINIT_CHECK("Freeing memory allocated by Py_DecodeLocale\n");
    PyMem_RawFree(program);
    return 0;
}


/* bpo-33042: Ensure embedding apps can predefine sys module options */
static int test_pre_initialization_sys_options(void)
{
    /* We allocate a couple of the options dynamically, and then delete
     * them before calling Py_Initialize. This ensures the interpreter isn't
     * relying on the caller to keep the passed in strings alive.
     */
    const wchar_t *static_warnoption = L"once";
    const wchar_t *static_xoption = L"also_not_an_option=2";
    size_t warnoption_len = wcslen(static_warnoption);
    size_t xoption_len = wcslen(static_xoption);
    wchar_t *dynamic_once_warnoption = \
             (wchar_t *) calloc(warnoption_len+1, sizeof(wchar_t));
    wchar_t *dynamic_xoption = \
             (wchar_t *) calloc(xoption_len+1, sizeof(wchar_t));
    wcsncpy(dynamic_once_warnoption, static_warnoption, warnoption_len+1);
    wcsncpy(dynamic_xoption, static_xoption, xoption_len+1);

    _Py_EMBED_PREINIT_CHECK("Checking PySys_AddWarnOption\n");
    PySys_AddWarnOption(L"default");
    _Py_EMBED_PREINIT_CHECK("Checking PySys_ResetWarnOptions\n");
    PySys_ResetWarnOptions();
    _Py_EMBED_PREINIT_CHECK("Checking PySys_AddWarnOption linked list\n");
    PySys_AddWarnOption(dynamic_once_warnoption);
    PySys_AddWarnOption(L"module");
    PySys_AddWarnOption(L"default");
    _Py_EMBED_PREINIT_CHECK("Checking PySys_AddXOption\n");
    PySys_AddXOption(L"not_an_option=1");
    PySys_AddXOption(dynamic_xoption);

    /* Delete the dynamic options early */
    free(dynamic_once_warnoption);
    dynamic_once_warnoption = NULL;
    free(dynamic_xoption);
    dynamic_xoption = NULL;

    _Py_EMBED_PREINIT_CHECK("Initializing interpreter\n");
    _testembed_Py_InitializeFromConfig();
    _Py_EMBED_PREINIT_CHECK("Check sys module contents\n");
    PyRun_SimpleString("import sys; "
                       "print('sys.warnoptions:', sys.warnoptions); "
                       "print('sys._xoptions:', sys._xoptions); "
                       "warnings = sys.modules['warnings']; "
                       "latest_filters = [f[0] for f in warnings.filters[:3]]; "
                       "print('warnings.filters[:3]:', latest_filters)");
    _Py_EMBED_PREINIT_CHECK("Finalizing interpreter\n");
    Py_Finalize();

    return 0;
}


/* bpo-20891: Avoid race condition when initialising the GIL */
static void bpo20891_thread(void *lockp)
{
    PyThread_type_lock lock = *((PyThread_type_lock*)lockp);

    PyGILState_STATE state = PyGILState_Ensure();
    if (!PyGILState_Check()) {
        error("PyGILState_Check failed!");
        abort();
    }

    PyGILState_Release(state);

    PyThread_release_lock(lock);
}

static int test_bpo20891(void)
{
    /* the test doesn't support custom memory allocators */
    putenv("PYTHONMALLOC=");

    /* bpo-20891: Calling PyGILState_Ensure in a non-Python thread must not
       crash. */
    PyThread_type_lock lock = PyThread_allocate_lock();
    if (!lock) {
        error("PyThread_allocate_lock failed!");
        return 1;
    }

    _testembed_Py_InitializeFromConfig();

    unsigned long thrd = PyThread_start_new_thread(bpo20891_thread, &lock);
    if (thrd == PYTHREAD_INVALID_THREAD_ID) {
        error("PyThread_start_new_thread failed!");
        return 1;
    }
    PyThread_acquire_lock(lock, WAIT_LOCK);

    Py_BEGIN_ALLOW_THREADS
    /* wait until the thread exit */
    PyThread_acquire_lock(lock, WAIT_LOCK);
    Py_END_ALLOW_THREADS

    PyThread_free_lock(lock);

    Py_Finalize();

    return 0;
}

static int test_initialize_twice(void)
{
    _testembed_Py_InitializeFromConfig();

    /* bpo-33932: Calling Py_Initialize() twice should do nothing
     * (and not crash!). */
    Py_Initialize();

    Py_Finalize();

    return 0;
}

static int test_initialize_pymain(void)
{
    wchar_t *argv[] = {L"PYTHON", L"-c",
                       (L"import sys; "
                        L"print(f'Py_Main() after Py_Initialize: "
                        L"sys.argv={sys.argv}')"),
                       L"arg2"};
    _testembed_Py_InitializeFromConfig();

    /* bpo-34008: Calling Py_Main() after Py_Initialize() must not crash */
    Py_Main(Py_ARRAY_LENGTH(argv), argv);

    Py_Finalize();

    return 0;
}


static void
dump_config(void)
{
    (void) PyRun_SimpleStringFlags(
        "import _testinternalcapi, json; "
        "print(json.dumps(_testinternalcapi.get_configs()))",
        0);
}


static int test_init_initialize_config(void)
{
    _testembed_Py_InitializeFromConfig();
    dump_config();
    Py_Finalize();
    return 0;
}


static void config_set_argv(PyConfig *config, Py_ssize_t argc, wchar_t * const *argv)
{
    PyStatus status = PyConfig_SetArgv(config, argc, argv);
    if (PyStatus_Exception(status)) {
        PyConfig_Clear(config);
        Py_ExitStatusException(status);
    }
}


static void
config_set_wide_string_list(PyConfig *config, PyWideStringList *list,
                            Py_ssize_t length, wchar_t **items)
{
    PyStatus status = PyConfig_SetWideStringList(config, list, length, items);
    if (PyStatus_Exception(status)) {
        PyConfig_Clear(config);
        Py_ExitStatusException(status);
    }
}


static int check_init_compat_config(int preinit)
{
    PyStatus status;

    if (preinit) {
        PyPreConfig preconfig;
        _PyPreConfig_InitCompatConfig(&preconfig);

        status = Py_PreInitialize(&preconfig);
        if (PyStatus_Exception(status)) {
            Py_ExitStatusException(status);
        }
    }

    PyConfig config;
    _PyConfig_InitCompatConfig(&config);

    config_set_program_name(&config);
    init_from_config_clear(&config);

    dump_config();
    Py_Finalize();
    return 0;
}


static int test_preinit_compat_config(void)
{
    return check_init_compat_config(1);
}


static int test_init_compat_config(void)
{
    return check_init_compat_config(0);
}


static int test_init_global_config(void)
{
    /* FIXME: test Py_IgnoreEnvironmentFlag */

    putenv("PYTHONUTF8=0");
    Py_UTF8Mode = 1;

    /* Test initialization from global configuration variables (Py_xxx) */
    Py_SetProgramName(L"./globalvar");

    /* Py_IsolatedFlag is not tested */
    Py_NoSiteFlag = 1;
    Py_BytesWarningFlag = 1;

    putenv("PYTHONINSPECT=");
    Py_InspectFlag = 1;

    putenv("PYTHONOPTIMIZE=0");
    Py_InteractiveFlag = 1;

    putenv("PYTHONDEBUG=0");
    Py_OptimizeFlag = 2;

    /* Py_DebugFlag is not tested */

    putenv("PYTHONDONTWRITEBYTECODE=");
    Py_DontWriteBytecodeFlag = 1;

    putenv("PYTHONVERBOSE=0");
    Py_VerboseFlag = 1;

    Py_QuietFlag = 1;
    Py_NoUserSiteDirectory = 1;

    putenv("PYTHONUNBUFFERED=");
    Py_UnbufferedStdioFlag = 1;

    Py_FrozenFlag = 1;

    /* FIXME: test Py_LegacyWindowsFSEncodingFlag */
    /* FIXME: test Py_LegacyWindowsStdioFlag */

    Py_Initialize();
    dump_config();
    Py_Finalize();
    return 0;
}


static int test_init_from_config(void)
{
    PyPreConfig preconfig;
    _PyPreConfig_InitCompatConfig(&preconfig);

    putenv("PYTHONMALLOC=malloc_debug");
#ifndef Py_GIL_DISABLED
    preconfig.allocator = PYMEM_ALLOCATOR_MALLOC;
#else
    preconfig.allocator = PYMEM_ALLOCATOR_MIMALLOC;
#endif

    putenv("PYTHONUTF8=0");
    Py_UTF8Mode = 0;
    preconfig.utf8_mode = 1;

    PyStatus status = Py_PreInitialize(&preconfig);
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }

    PyConfig config;
    _PyConfig_InitCompatConfig(&config);

    config.install_signal_handlers = 0;

    /* FIXME: test use_environment */

    putenv("PYTHONHASHSEED=42");
    config.use_hash_seed = 1;
    config.hash_seed = 123;

    /* dev_mode=1 is tested in test_init_dev_mode() */

    putenv("PYTHONFAULTHANDLER=");
    config.faulthandler = 1;

    putenv("PYTHONTRACEMALLOC=0");
    config.tracemalloc = 2;

    putenv("PYTHONPROFILEIMPORTTIME=0");
    config.import_time = 1;

    putenv("PYTHONNODEBUGRANGES=0");
    config.code_debug_ranges = 0;

    config.show_ref_count = 1;
    /* FIXME: test dump_refs: bpo-34223 */

    putenv("PYTHONMALLOCSTATS=0");
    config.malloc_stats = 1;

    putenv("PYTHONPYCACHEPREFIX=env_pycache_prefix");
    config_set_string(&config, &config.pycache_prefix, L"conf_pycache_prefix");

    Py_SetProgramName(L"./globalvar");
    config_set_string(&config, &config.program_name, L"./conf_program_name");

    wchar_t* argv[] = {
        L"python3",
        L"-W",
        L"cmdline_warnoption",
        L"-X",
        L"cmdline_xoption",
        L"-c",
        L"pass",
        L"arg2",
    };
    config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
    config.parse_argv = 1;

    wchar_t* xoptions[3] = {
        L"config_xoption1=3",
        L"config_xoption2=",
        L"config_xoption3",
    };
    config_set_wide_string_list(&config, &config.xoptions,
                                Py_ARRAY_LENGTH(xoptions), xoptions);

    wchar_t* warnoptions[1] = {
        L"config_warnoption",
    };
    config_set_wide_string_list(&config, &config.warnoptions,
                                Py_ARRAY_LENGTH(warnoptions), warnoptions);

    /* FIXME: test pythonpath_env */
    /* FIXME: test home */
    /* FIXME: test path config: module_search_path .. dll_path */

    putenv("PYTHONPLATLIBDIR=env_platlibdir");
    config_set_string(&config, &config.platlibdir, L"my_platlibdir");

    putenv("PYTHONVERBOSE=0");
    Py_VerboseFlag = 0;
    config.verbose = 1;

    Py_NoSiteFlag = 0;
    config.site_import = 0;

    Py_BytesWarningFlag = 0;
    config.bytes_warning = 1;

    putenv("PYTHONINSPECT=");
    Py_InspectFlag = 0;
    config.inspect = 1;

    Py_InteractiveFlag = 0;
    config.interactive = 1;

    putenv("PYTHONOPTIMIZE=0");
    Py_OptimizeFlag = 1;
    config.optimization_level = 2;

    /* FIXME: test parser_debug */

    putenv("PYTHONDONTWRITEBYTECODE=");
    Py_DontWriteBytecodeFlag = 0;
    config.write_bytecode = 0;

    Py_QuietFlag = 0;
    config.quiet = 1;

    config.configure_c_stdio = 1;

    putenv("PYTHONUNBUFFERED=");
    Py_UnbufferedStdioFlag = 0;
    config.buffered_stdio = 0;

    putenv("PYTHONIOENCODING=cp424");
    config_set_string(&config, &config.stdio_encoding, L"iso8859-1");
    config_set_string(&config, &config.stdio_errors, L"replace");

    putenv("PYTHONNOUSERSITE=");
    Py_NoUserSiteDirectory = 0;
    config.user_site_directory = 0;

    config_set_string(&config, &config.check_hash_pycs_mode, L"always");

    Py_FrozenFlag = 0;
    config.pathconfig_warnings = 0;

    config.safe_path = 1;
#ifdef Py_STATS
    putenv("PYTHONSTATS=");
    config._pystats = 1;
#endif

    putenv("PYTHONINTMAXSTRDIGITS=6666");
    config.int_max_str_digits = 31337;
    config.cpu_count = 4321;

    init_from_config_clear(&config);

    dump_config();
    Py_Finalize();
    return 0;
}


static int check_init_parse_argv(int parse_argv)
{
    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    config.parse_argv = parse_argv;

    wchar_t* argv[] = {
        L"./argv0",
        L"-E",
        L"-c",
        L"pass",
        L"arg1",
        L"-v",
        L"arg3",
    };
    config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
    init_from_config_clear(&config);

    dump_config();
    Py_Finalize();
    return 0;
}


static int test_init_parse_argv(void)
{
    return check_init_parse_argv(1);
}


static int test_init_dont_parse_argv(void)
{
    return check_init_parse_argv(0);
}


static void set_most_env_vars(void)
{
    putenv("PYTHONHASHSEED=42");
#ifndef Py_GIL_DISABLED
    putenv("PYTHONMALLOC=malloc");
#else
    putenv("PYTHONMALLOC=mimalloc");
#endif
    putenv("PYTHONTRACEMALLOC=2");
    putenv("PYTHONPROFILEIMPORTTIME=1");
    putenv("PYTHONNODEBUGRANGES=1");
    putenv("PYTHONMALLOCSTATS=1");
    putenv("PYTHONUTF8=1");
    putenv("PYTHONVERBOSE=1");
    putenv("PYTHONINSPECT=1");
    putenv("PYTHONOPTIMIZE=2");
    putenv("PYTHONDONTWRITEBYTECODE=1");
    putenv("PYTHONUNBUFFERED=1");
    putenv("PYTHONPYCACHEPREFIX=env_pycache_prefix");
    putenv("PYTHONNOUSERSITE=1");
    putenv("PYTHONFAULTHANDLER=1");
    putenv("PYTHONIOENCODING=iso8859-1:replace");
    putenv("PYTHONPLATLIBDIR=env_platlibdir");
    putenv("PYTHONSAFEPATH=1");
    putenv("PYTHONINTMAXSTRDIGITS=4567");
#ifdef Py_STATS
    putenv("PYTHONSTATS=1");
#endif
}


static void set_all_env_vars(void)
{
    set_most_env_vars();

    putenv("PYTHONWARNINGS=EnvVar");
    putenv("PYTHONPATH=/my/path");
}


static int test_init_compat_env(void)
{
    /* Test initialization from environment variables */
    Py_IgnoreEnvironmentFlag = 0;
    set_all_env_vars();
    _testembed_Py_InitializeFromConfig();
    dump_config();
    Py_Finalize();
    return 0;
}


static int test_init_python_env(void)
{
    set_all_env_vars();

    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    config_set_program_name(&config);
    init_from_config_clear(&config);

    dump_config();
    Py_Finalize();
    return 0;
}


static void set_all_env_vars_dev_mode(void)
{
    putenv("PYTHONMALLOC=");
    putenv("PYTHONFAULTHANDLER=");
    putenv("PYTHONDEVMODE=1");
}


static int test_init_env_dev_mode(void)
{
    /* Test initialization from environment variables */
    Py_IgnoreEnvironmentFlag = 0;
    set_all_env_vars_dev_mode();
    _testembed_Py_InitializeFromConfig();
    dump_config();
    Py_Finalize();
    return 0;
}


static int test_init_env_dev_mode_alloc(void)
{
    /* Test initialization from environment variables */
    Py_IgnoreEnvironmentFlag = 0;
    set_all_env_vars_dev_mode();
#ifndef Py_GIL_DISABLED
    putenv("PYTHONMALLOC=malloc");
#else
    putenv("PYTHONMALLOC=mimalloc");
#endif
    _testembed_Py_InitializeFromConfig();
    dump_config();
    Py_Finalize();
    return 0;
}


static int test_init_isolated_flag(void)
{
    /* Test PyConfig.isolated=1 */
    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    Py_IsolatedFlag = 0;
    config.isolated = 1;
    // These options are set to 1 by isolated=1
    config.safe_path = 0;
    config.use_environment = 1;
    config.user_site_directory = 1;

    config_set_program_name(&config);
    set_all_env_vars();
    init_from_config_clear(&config);

    dump_config();
    Py_Finalize();
    return 0;
}


/* PyPreConfig.isolated=1, PyConfig.isolated=0 */
static int test_preinit_isolated1(void)
{
    PyPreConfig preconfig;
    _PyPreConfig_InitCompatConfig(&preconfig);

    preconfig.isolated = 1;

    PyStatus status = Py_PreInitialize(&preconfig);
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }

    PyConfig config;
    _PyConfig_InitCompatConfig(&config);

    config_set_program_name(&config);
    set_all_env_vars();
    init_from_config_clear(&config);

    dump_config();
    Py_Finalize();
    return 0;
}


/* PyPreConfig.isolated=0, PyConfig.isolated=1 */
static int test_preinit_isolated2(void)
{
    PyPreConfig preconfig;
    _PyPreConfig_InitCompatConfig(&preconfig);

    preconfig.isolated = 0;

    PyStatus status = Py_PreInitialize(&preconfig);
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }

    /* Test PyConfig.isolated=1 */
    PyConfig config;
    _PyConfig_InitCompatConfig(&config);

    Py_IsolatedFlag = 0;
    config.isolated = 1;

    config_set_program_name(&config);
    set_all_env_vars();
    init_from_config_clear(&config);

    dump_config();
    Py_Finalize();
    return 0;
}


static int test_preinit_dont_parse_argv(void)
{
    PyPreConfig preconfig;
    PyPreConfig_InitIsolatedConfig(&preconfig);

    preconfig.isolated = 0;

    /* -X dev must be ignored by isolated preconfiguration */
    wchar_t *argv[] = {L"python3",
                       L"-E",
                       L"-I",
                       L"-P",
                       L"-X", L"dev",
                       L"-X", L"utf8",
                       L"script.py"};
    PyStatus status = Py_PreInitializeFromArgs(&preconfig,
                                               Py_ARRAY_LENGTH(argv), argv);
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }

    PyConfig config;
    PyConfig_InitIsolatedConfig(&config);

    config.isolated = 0;

    /* Pre-initialize implicitly using argv: make sure that -X dev
       is used to configure the allocation in preinitialization */
    config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
    config_set_program_name(&config);
    init_from_config_clear(&config);

    dump_config();
    Py_Finalize();
    return 0;
}


static int test_preinit_parse_argv(void)
{
    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    /* Pre-initialize implicitly using argv: make sure that -X dev
       is used to configure the allocation in preinitialization */
    wchar_t *argv[] = {L"python3", L"-X", L"dev", L"-P", L"script.py"};
    config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
    config_set_program_name(&config);
    init_from_config_clear(&config);

    dump_config();
    Py_Finalize();
    return 0;
}




static void set_all_global_config_variables(void)
{
    Py_IsolatedFlag = 0;
    Py_IgnoreEnvironmentFlag = 0;
    Py_BytesWarningFlag = 2;
    Py_InspectFlag = 1;
    Py_InteractiveFlag = 1;
    Py_OptimizeFlag = 1;
    Py_DebugFlag = 1;
    Py_VerboseFlag = 1;
    Py_QuietFlag = 1;
    Py_FrozenFlag = 0;
    Py_UnbufferedStdioFlag = 1;
    Py_NoSiteFlag = 1;
    Py_DontWriteBytecodeFlag = 1;
    Py_NoUserSiteDirectory = 1;
#ifdef MS_WINDOWS
    Py_LegacyWindowsStdioFlag = 1;
#endif
}


static int check_preinit_isolated_config(int preinit)
{
    PyStatus status;
    PyPreConfig *rt_preconfig;

    /* environment variables must be ignored */
    set_all_env_vars();

    /* global configuration variables must be ignored */
    set_all_global_config_variables();

    if (preinit) {
        PyPreConfig preconfig;
        PyPreConfig_InitIsolatedConfig(&preconfig);

        status = Py_PreInitialize(&preconfig);
        if (PyStatus_Exception(status)) {
            Py_ExitStatusException(status);
        }

        rt_preconfig = &_PyRuntime.preconfig;
        assert(rt_preconfig->isolated == 1);
        assert(rt_preconfig->use_environment == 0);
    }

    PyConfig config;
    PyConfig_InitIsolatedConfig(&config);

    config_set_program_name(&config);
    init_from_config_clear(&config);

    rt_preconfig = &_PyRuntime.preconfig;
    assert(rt_preconfig->isolated == 1);
    assert(rt_preconfig->use_environment == 0);

    dump_config();
    Py_Finalize();
    return 0;
}


static int test_preinit_isolated_config(void)
{
    return check_preinit_isolated_config(1);
}


static int test_init_isolated_config(void)
{
    return check_preinit_isolated_config(0);
}


static int check_init_python_config(int preinit)
{
    /* global configuration variables must be ignored */
    set_all_global_config_variables();
    Py_IsolatedFlag = 1;
    Py_IgnoreEnvironmentFlag = 1;
    Py_FrozenFlag = 1;
    Py_UnbufferedStdioFlag = 1;
    Py_NoSiteFlag = 1;
    Py_DontWriteBytecodeFlag = 1;
    Py_NoUserSiteDirectory = 1;
#ifdef MS_WINDOWS
    Py_LegacyWindowsStdioFlag = 1;
#endif

    if (preinit) {
        PyPreConfig preconfig;
        PyPreConfig_InitPythonConfig(&preconfig);

        PyStatus status = Py_PreInitialize(&preconfig);
        if (PyStatus_Exception(status)) {
            Py_ExitStatusException(status);
        }
    }

    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    config_set_program_name(&config);
    init_from_config_clear(&config);

    dump_config();
    Py_Finalize();
    return 0;
}


static int test_preinit_python_config(void)
{
    return check_init_python_config(1);
}


static int test_init_python_config(void)
{
    return check_init_python_config(0);
}


static int test_init_dont_configure_locale(void)
{
    PyPreConfig preconfig;
    PyPreConfig_InitPythonConfig(&preconfig);

    preconfig.configure_locale = 0;
    preconfig.coerce_c_locale = 1;
    preconfig.coerce_c_locale_warn = 1;

    PyStatus status = Py_PreInitialize(&preconfig);
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }

    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    config_set_program_name(&config);
    init_from_config_clear(&config);

    dump_config();
    Py_Finalize();
    return 0;
}


static int test_init_dev_mode(void)
{
    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    putenv("PYTHONFAULTHANDLER=");
    putenv("PYTHONMALLOC=");
    config.dev_mode = 1;
    config_set_program_name(&config);
    init_from_config_clear(&config);

    dump_config();
    Py_Finalize();
    return 0;
}

static PyObject *_open_code_hook(PyObject *path, void *data)
{
    if (PyUnicode_CompareWithASCIIString(path, "$$test-filename") == 0) {
        return PyLong_FromVoidPtr(data);
    }
    PyObject *io = PyImport_ImportModule("_io");
    if (!io) {
        return NULL;
    }
    return PyObject_CallMethod(io, "open", "Os", path, "rb");
}

static int test_open_code_hook(void)
{
    int result = 0;

    /* Provide a hook */
    result = PyFile_SetOpenCodeHook(_open_code_hook, &result);
    if (result) {
        printf("Failed to set hook\n");
        return 1;
    }
    /* A second hook should fail */
    result = PyFile_SetOpenCodeHook(_open_code_hook, &result);
    if (!result) {
        printf("Should have failed to set second hook\n");
        return 2;
    }

    Py_IgnoreEnvironmentFlag = 0;
    _testembed_Py_InitializeFromConfig();
    result = 0;

    PyObject *r = PyFile_OpenCode("$$test-filename");
    if (!r) {
        PyErr_Print();
        result = 3;
    } else {
        void *cmp = PyLong_AsVoidPtr(r);
        Py_DECREF(r);
        if (cmp != &result) {
            printf("Did not get expected result from hook\n");
            result = 4;
        }
    }

    if (!result) {
        PyObject *io = PyImport_ImportModule("_io");
        PyObject *r = io
            ? PyObject_CallMethod(io, "open_code", "s", "$$test-filename")
            : NULL;
        if (!r) {
            PyErr_Print();
            result = 5;
        } else {
            void *cmp = PyLong_AsVoidPtr(r);
            Py_DECREF(r);
            if (cmp != &result) {
                printf("Did not get expected result from hook\n");
                result = 6;
            }
        }
        Py_XDECREF(io);
    }

    Py_Finalize();
    return result;
}

static int _audit_hook_clear_count = 0;

static int _audit_hook(const char *event, PyObject *args, void *userdata)
{
    assert(args && PyTuple_CheckExact(args));
    if (strcmp(event, "_testembed.raise") == 0) {
        PyErr_SetString(PyExc_RuntimeError, "Intentional error");
        return -1;
    } else if (strcmp(event, "_testembed.set") == 0) {
        if (!PyArg_ParseTuple(args, "n", userdata)) {
            return -1;
        }
        return 0;
    } else if (strcmp(event, "cpython._PySys_ClearAuditHooks") == 0) {
        _audit_hook_clear_count += 1;
    }
    return 0;
}

static int _test_audit(Py_ssize_t setValue)
{
    Py_ssize_t sawSet = 0;

    Py_IgnoreEnvironmentFlag = 0;
    PySys_AddAuditHook(_audit_hook, &sawSet);
    _testembed_Py_InitializeFromConfig();

    if (PySys_Audit("_testembed.raise", NULL) == 0) {
        printf("No error raised");
        return 1;
    }
    if (PySys_Audit("_testembed.nop", NULL) != 0) {
        printf("Nop event failed");
        /* Exception from above may still remain */
        PyErr_Clear();
        return 2;
    }
    if (!PyErr_Occurred()) {
        printf("Exception not preserved");
        return 3;
    }
    PyErr_Clear();

    if (PySys_Audit("_testembed.set", "n", setValue) != 0) {
        PyErr_Print();
        printf("Set event failed");
        return 4;
    }
    if (PyErr_Occurred()) {
        printf("Exception raised");
        return 5;
    }

    if (sawSet != 42) {
        printf("Failed to see *userData change\n");
        return 6;
    }

    return 0;
}

static int test_audit(void)
{
    int result = _test_audit(42);
    Py_Finalize();
    if (_audit_hook_clear_count != 1) {
        return 0x1000 | _audit_hook_clear_count;
    }
    return result;
}

static int test_audit_tuple(void)
{
#define ASSERT(TEST, EXITCODE) \
    if (!(TEST)) { \
        printf("ERROR test failed at %s:%i\n", __FILE__, __LINE__); \
        return (EXITCODE); \
    }

    Py_ssize_t sawSet = 0;

    // we need at least one hook, otherwise code checking for
    // PySys_AuditTuple() is skipped.
    PySys_AddAuditHook(_audit_hook, &sawSet);
    _testembed_Py_InitializeFromConfig();

    ASSERT(!PyErr_Occurred(), 0);

    // pass Python tuple object
    PyObject *tuple = Py_BuildValue("(i)", 444);
    if (tuple == NULL) {
        goto error;
    }
    ASSERT(PySys_AuditTuple("_testembed.set", tuple) == 0, 10);
    ASSERT(!PyErr_Occurred(), 11);
    ASSERT(sawSet == 444, 12);
    Py_DECREF(tuple);

    // pass Python int object
    PyObject *int_arg = PyLong_FromLong(555);
    if (int_arg == NULL) {
        goto error;
    }
    ASSERT(PySys_AuditTuple("_testembed.set", int_arg) == -1, 20);
    ASSERT(PyErr_ExceptionMatches(PyExc_TypeError), 21);
    PyErr_Clear();
    Py_DECREF(int_arg);

    // NULL is accepted and means "no arguments"
    ASSERT(PySys_AuditTuple("_testembed.test_audit_tuple", NULL) == 0, 30);
    ASSERT(!PyErr_Occurred(), 31);

    Py_Finalize();
    return 0;

error:
    PyErr_Print();
    return 1;

#undef ASSERT
}

static volatile int _audit_subinterpreter_interpreter_count = 0;

static int _audit_subinterpreter_hook(const char *event, PyObject *args, void *userdata)
{
    printf("%s\n", event);
    if (strcmp(event, "cpython.PyInterpreterState_New") == 0) {
        _audit_subinterpreter_interpreter_count += 1;
    }
    return 0;
}

static int test_audit_subinterpreter(void)
{
    Py_IgnoreEnvironmentFlag = 0;
    PySys_AddAuditHook(_audit_subinterpreter_hook, NULL);
    _testembed_Py_InitializeFromConfig();

    Py_NewInterpreter();
    Py_NewInterpreter();
    Py_NewInterpreter();

    Py_Finalize();

    switch (_audit_subinterpreter_interpreter_count) {
        case 3: return 0;
        case 0: return -1;
        default: return _audit_subinterpreter_interpreter_count;
    }
}

typedef struct {
    const char* expected;
    int exit;
} AuditRunCommandTest;

static int _audit_hook_run(const char *eventName, PyObject *args, void *userData)
{
    AuditRunCommandTest *test = (AuditRunCommandTest*)userData;
    if (strcmp(eventName, test->expected)) {
        return 0;
    }

    if (test->exit) {
        PyObject *msg = PyUnicode_FromFormat("detected %s(%R)", eventName, args);
        if (msg) {
            printf("%s\n", PyUnicode_AsUTF8(msg));
            Py_DECREF(msg);
        }
        exit(test->exit);
    }

    PyErr_Format(PyExc_RuntimeError, "detected %s(%R)", eventName, args);
    return -1;
}

static int test_audit_run_command(void)
{
    AuditRunCommandTest test = {"cpython.run_command"};
    wchar_t *argv[] = {PROGRAM_NAME, L"-c", L"pass"};

    Py_IgnoreEnvironmentFlag = 0;
    PySys_AddAuditHook(_audit_hook_run, (void*)&test);

    return Py_Main(Py_ARRAY_LENGTH(argv), argv);
}

static int test_audit_run_file(void)
{
    AuditRunCommandTest test = {"cpython.run_file"};
    wchar_t *argv[] = {PROGRAM_NAME, L"filename.py"};

    Py_IgnoreEnvironmentFlag = 0;
    PySys_AddAuditHook(_audit_hook_run, (void*)&test);

    return Py_Main(Py_ARRAY_LENGTH(argv), argv);
}

static int run_audit_run_test(int argc, wchar_t **argv, void *test)
{
    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    config.argv.length = argc;
    config.argv.items = argv;
    config.parse_argv = 1;
    config.program_name = argv[0];
    config.interactive = 1;
    config.isolated = 0;
    config.use_environment = 1;
    config.quiet = 1;

    PySys_AddAuditHook(_audit_hook_run, test);

    PyStatus status = Py_InitializeFromConfig(&config);
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }

    return Py_RunMain();
}

static int test_audit_run_interactivehook(void)
{
    AuditRunCommandTest test = {"cpython.run_interactivehook", 10};
    wchar_t *argv[] = {PROGRAM_NAME};
    return run_audit_run_test(Py_ARRAY_LENGTH(argv), argv, &test);
}

static int test_audit_run_startup(void)
{
    AuditRunCommandTest test = {"cpython.run_startup", 10};
    wchar_t *argv[] = {PROGRAM_NAME};
    return run_audit_run_test(Py_ARRAY_LENGTH(argv), argv, &test);
}

static int test_audit_run_stdin(void)
{
    AuditRunCommandTest test = {"cpython.run_stdin"};
    wchar_t *argv[] = {PROGRAM_NAME};
    return run_audit_run_test(Py_ARRAY_LENGTH(argv), argv, &test);
}

static int test_init_read_set(void)
{
    PyStatus status;
    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    config_set_string(&config, &config.program_name, L"./init_read_set");

    status = PyConfig_Read(&config);
    if (PyStatus_Exception(status)) {
        goto fail;
    }

    status = PyWideStringList_Insert(&config.module_search_paths,
                                     1, L"test_path_insert1");
    if (PyStatus_Exception(status)) {
        goto fail;
    }

    status = PyWideStringList_Append(&config.module_search_paths,
                                     L"test_path_append");
    if (PyStatus_Exception(status)) {
        goto fail;
    }

    /* override executable computed by PyConfig_Read() */
    config_set_string(&config, &config.executable, L"my_executable");
    init_from_config_clear(&config);

    dump_config();
    Py_Finalize();
    return 0;

fail:
    PyConfig_Clear(&config);
    Py_ExitStatusException(status);
}


static int test_init_sys_add(void)
{
    PySys_AddXOption(L"sysadd_xoption");
    PySys_AddXOption(L"faulthandler");
    PySys_AddWarnOption(L"ignore:::sysadd_warnoption");

    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    wchar_t* argv[] = {
        L"python3",
        L"-W",
        L"ignore:::cmdline_warnoption",
        L"-X",
        L"cmdline_xoption",
    };
    config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
    config.parse_argv = 1;

    PyStatus status;
    status = PyWideStringList_Append(&config.xoptions,
                                     L"config_xoption");
    if (PyStatus_Exception(status)) {
        goto fail;
    }

    status = PyWideStringList_Append(&config.warnoptions,
                                     L"ignore:::config_warnoption");
    if (PyStatus_Exception(status)) {
        goto fail;
    }

    config_set_program_name(&config);
    init_from_config_clear(&config);

    dump_config();
    Py_Finalize();
    return 0;

fail:
    PyConfig_Clear(&config);
    Py_ExitStatusException(status);
}


static int test_init_setpath(void)
{
    char *env = getenv("TESTPATH");
    if (!env) {
        error("missing TESTPATH env var");
        return 1;
    }
    wchar_t *path = Py_DecodeLocale(env, NULL);
    if (path == NULL) {
        error("failed to decode TESTPATH");
        return 1;
    }
    Py_SetPath(path);
    PyMem_RawFree(path);
    putenv("TESTPATH=");

    Py_Initialize();
    dump_config();
    Py_Finalize();
    return 0;
}


static int test_init_setpath_config(void)
{
    PyPreConfig preconfig;
    PyPreConfig_InitPythonConfig(&preconfig);

    /* Explicitly preinitializes with Python preconfiguration to avoid
      Py_SetPath() implicit preinitialization with compat preconfiguration. */
    PyStatus status = Py_PreInitialize(&preconfig);
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }

    char *env = getenv("TESTPATH");
    if (!env) {
        error("missing TESTPATH env var");
        return 1;
    }
    wchar_t *path = Py_DecodeLocale(env, NULL);
    if (path == NULL) {
        error("failed to decode TESTPATH");
        return 1;
    }
    Py_SetPath(path);
    PyMem_RawFree(path);
    putenv("TESTPATH=");

    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    config_set_string(&config, &config.program_name, L"conf_program_name");
    config_set_string(&config, &config.executable, L"conf_executable");
    init_from_config_clear(&config);

    dump_config();
    Py_Finalize();
    return 0;
}


static int test_init_setpythonhome(void)
{
    char *env = getenv("TESTHOME");
    if (!env) {
        error("missing TESTHOME env var");
        return 1;
    }
    wchar_t *home = Py_DecodeLocale(env, NULL);
    if (home == NULL) {
        error("failed to decode TESTHOME");
        return 1;
    }
    Py_SetPythonHome(home);
    PyMem_RawFree(home);
    putenv("TESTHOME=");

    Py_Initialize();
    dump_config();
    Py_Finalize();
    return 0;
}


static int test_init_is_python_build(void)
{
    // gh-91985: in-tree builds fail to check for build directory landmarks
    // under the effect of 'home' or PYTHONHOME environment variable.
    char *env = getenv("TESTHOME");
    if (!env) {
        error("missing TESTHOME env var");
        return 1;
    }
    wchar_t *home = Py_DecodeLocale(env, NULL);
    if (home == NULL) {
        error("failed to decode TESTHOME");
        return 1;
    }

    PyConfig config;
    _PyConfig_InitCompatConfig(&config);
    config_set_program_name(&config);
    config_set_string(&config, &config.home, home);
    PyMem_RawFree(home);
    putenv("TESTHOME=");

    // Use an impossible value so we can detect whether it isn't updated
    // during initialization.
    config._is_python_build = INT_MAX;
    env = getenv("NEGATIVE_ISPYTHONBUILD");
    if (env && strcmp(env, "0") != 0) {
        config._is_python_build = INT_MIN;
    }
    init_from_config_clear(&config);
    Py_Finalize();
    // Second initialization
    config._is_python_build = -1;
    init_from_config_clear(&config);
    dump_config();  // home and _is_python_build are cached in _Py_path_config
    Py_Finalize();
    return 0;
}


static int test_init_warnoptions(void)
{
    putenv("PYTHONWARNINGS=ignore:::env1,ignore:::env2");

    PySys_AddWarnOption(L"ignore:::PySys_AddWarnOption1");
    PySys_AddWarnOption(L"ignore:::PySys_AddWarnOption2");

    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    config.dev_mode = 1;
    config.bytes_warning = 1;

    config_set_program_name(&config);

    PyStatus status;
    status = PyWideStringList_Append(&config.warnoptions,
                                     L"ignore:::PyConfig_BeforeRead");
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }

    wchar_t* argv[] = {
        L"python3",
        L"-Wignore:::cmdline1",
        L"-Wignore:::cmdline2"};
    config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
    config.parse_argv = 1;

    status = PyConfig_Read(&config);
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }

    status = PyWideStringList_Append(&config.warnoptions,
                                     L"ignore:::PyConfig_AfterRead");
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }

    status = PyWideStringList_Insert(&config.warnoptions,
                                     0, L"ignore:::PyConfig_Insert0");
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }

    init_from_config_clear(&config);
    dump_config();
    Py_Finalize();
    return 0;
}


static int tune_config(void)
{
    PyConfig config;
    PyConfig_InitPythonConfig(&config);
    if (_PyInterpreterState_GetConfigCopy(&config) < 0) {
        PyConfig_Clear(&config);
        PyErr_Print();
        return -1;
    }

    config.bytes_warning = 2;

    if (_PyInterpreterState_SetConfig(&config) < 0) {
        PyConfig_Clear(&config);
        return -1;
    }
    PyConfig_Clear(&config);
    return 0;
}


static int test_init_set_config(void)
{
    // Initialize core
    PyConfig config;
    PyConfig_InitIsolatedConfig(&config);
    config_set_string(&config, &config.program_name, PROGRAM_NAME);
    config._init_main = 0;
    config.bytes_warning = 0;
    init_from_config_clear(&config);

    // Tune the configuration using _PyInterpreterState_SetConfig()
    if (tune_config() < 0) {
        PyErr_Print();
        return 1;
    }

    // Finish initialization: main part
    PyStatus status = _Py_InitializeMain();
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }

    dump_config();
    Py_Finalize();
    return 0;
}


static void configure_init_main(PyConfig *config)
{
    wchar_t* argv[] = {
        L"python3", L"-c",
        (L"import _testinternalcapi, json; "
         L"print(json.dumps(_testinternalcapi.get_configs()))"),
        L"arg2"};

    config->parse_argv = 1;

    config_set_argv(config, Py_ARRAY_LENGTH(argv), argv);
    config_set_string(config, &config->program_name, L"./python3");
}


static int test_init_run_main(void)
{
    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    configure_init_main(&config);
    init_from_config_clear(&config);

    return Py_RunMain();
}


static int test_init_main(void)
{
    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    configure_init_main(&config);
    config._init_main = 0;
    init_from_config_clear(&config);

    /* sys.stdout don't exist yet: it is created by _Py_InitializeMain() */
    int res = PyRun_SimpleString(
        "import sys; "
        "print('Run Python code before _Py_InitializeMain', "
               "file=sys.stderr)");
    if (res < 0) {
        exit(1);
    }

    PyStatus status = _Py_InitializeMain();
    if (PyStatus_Exception(status)) {
        Py_ExitStatusException(status);
    }

    return Py_RunMain();
}


static int test_run_main(void)
{
    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    wchar_t *argv[] = {L"python3", L"-c",
                       (L"import sys; "
                        L"print(f'Py_RunMain(): sys.argv={sys.argv}')"),
                       L"arg2"};
    config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
    config_set_string(&config, &config.program_name, L"./python3");
    init_from_config_clear(&config);

    return Py_RunMain();
}


static int test_run_main_loop(void)
{
    // bpo-40413: Calling Py_InitializeFromConfig()+Py_RunMain() multiple
    // times must not crash.
    for (int i=0; i<5; i++) {
        int exitcode = test_run_main();
        if (exitcode != 0) {
            return exitcode;
        }
    }
    return 0;
}


static int test_get_argc_argv(void)
{
    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    wchar_t *argv[] = {L"python3", L"-c", L"pass", L"arg2"};
    config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
    config_set_string(&config, &config.program_name, L"./python3");

    // Calling PyConfig_Read() twice must not change Py_GetArgcArgv() result.
    // The second call is done by Py_InitializeFromConfig().
    PyStatus status = PyConfig_Read(&config);
    if (PyStatus_Exception(status)) {
        PyConfig_Clear(&config);
        Py_ExitStatusException(status);
    }

    init_from_config_clear(&config);

    int get_argc;
    wchar_t **get_argv;
    Py_GetArgcArgv(&get_argc, &get_argv);
    printf("argc: %i\n", get_argc);
    assert(get_argc == Py_ARRAY_LENGTH(argv));
    for (int i=0; i < get_argc; i++) {
        printf("argv[%i]: %ls\n", i, get_argv[i]);
        assert(wcscmp(get_argv[i], argv[i]) == 0);
    }

    Py_Finalize();

    printf("\n");
    printf("test ok\n");
    return 0;
}


static int check_use_frozen_modules(const char *rawval)
{
    wchar_t optval[100];
    if (rawval == NULL) {
        wcscpy(optval, L"frozen_modules");
    }
    else if (swprintf(optval, 100,
#if defined(_MSC_VER)
        L"frozen_modules=%S",
#else
        L"frozen_modules=%s",
#endif
        rawval) < 0) {
        error("rawval is too long");
        return -1;
    }

    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    config.parse_argv = 1;

    wchar_t* argv[] = {
        L"./argv0",
        L"-X",
        optval,
        L"-c",
        L"pass",
    };
    config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
    init_from_config_clear(&config);

    dump_config();
    Py_Finalize();
    return 0;
}

static int test_init_use_frozen_modules(void)
{
    const char *envvar = getenv("TESTFROZEN");
    return check_use_frozen_modules(envvar);
}


static int test_unicode_id_init(void)
{
    // bpo-42882: Test that _PyUnicode_FromId() works
    // when Python is initialized multiples times.

    // This is equivalent to `_Py_IDENTIFIER(test_unicode_id_init)`
    // but since `_Py_IDENTIFIER` is disabled when `Py_BUILD_CORE`
    // is defined, it is manually expanded here.
    static _Py_Identifier PyId_test_unicode_id_init = {
        .string = "test_unicode_id_init",
        .index = -1,
    };

    // Initialize Python once without using the identifier
    _testembed_Py_InitializeFromConfig();
    Py_Finalize();

    // Now initialize Python multiple times and use the identifier.
    // The first _PyUnicode_FromId() call initializes the identifier index.
    for (int i=0; i<3; i++) {
        _testembed_Py_InitializeFromConfig();

        PyObject *str1, *str2;

        str1 = _PyUnicode_FromId(&PyId_test_unicode_id_init);
        assert(str1 != NULL);
        assert(_Py_IsImmortal(str1));

        str2 = PyUnicode_FromString("test_unicode_id_init");
        assert(str2 != NULL);

        assert(PyUnicode_Compare(str1, str2) == 0);

        Py_DECREF(str2);

        Py_Finalize();
    }
    return 0;
}


static int test_init_main_interpreter_settings(void)
{
    _testembed_Py_Initialize();
    (void) PyRun_SimpleStringFlags(
        "import _testinternalcapi, json; "
        "print(json.dumps(_testinternalcapi.get_interp_settings(0)))",
        0);
    Py_Finalize();
    return 0;
}


#ifndef MS_WINDOWS
#include "test_frozenmain.h"      // M_test_frozenmain

static int test_frozenmain(void)
{
    static struct _frozen frozen_modules[4] = {
        {"__main__", M_test_frozenmain, sizeof(M_test_frozenmain)},
        {0, 0, 0}   // sentinel
    };

    char* argv[] = {
        "./argv0",
        "-E",
        "arg1",
        "arg2",
    };
    PyImport_FrozenModules = frozen_modules;
    return Py_FrozenMain(Py_ARRAY_LENGTH(argv), argv);
}
#endif  // !MS_WINDOWS

static int test_repeated_init_and_inittab(void)
{
    // bpo-44441: Py_RunMain() must reset PyImport_Inittab at exit.
    // It must be possible to call PyImport_AppendInittab() or
    // PyImport_ExtendInittab() before each Python initialization.
    for (int i=1; i <= INIT_LOOPS; i++) {
        printf("--- Pass %d ---\n", i);

        // Call PyImport_AppendInittab() at each iteration
        if (PyImport_AppendInittab(EMBEDDED_EXT_NAME,
                                   &PyInit_embedded_ext) != 0) {
            fprintf(stderr, "PyImport_AppendInittab() failed\n");
            return 1;
        }

        // Initialize Python
        wchar_t* argv[] = {PROGRAM_NAME, L"-c", L"pass"};
        PyConfig config;
        PyConfig_InitPythonConfig(&config);
        config.isolated = 1;
        config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
        init_from_config_clear(&config);

        // Py_RunMain() calls _PyImport_Fini2() which resets PyImport_Inittab
        int exitcode = Py_RunMain();
        if (exitcode != 0) {
            return exitcode;
        }
    }
    return 0;
}

static void wrap_allocator(PyMemAllocatorEx *allocator);
static void unwrap_allocator(PyMemAllocatorEx *allocator);

static void *
malloc_wrapper(void *ctx, size_t size)
{
    PyMemAllocatorEx *allocator = (PyMemAllocatorEx *)ctx;
    unwrap_allocator(allocator);
    PyEval_GetFrame();  // BOOM!
    wrap_allocator(allocator);
    return allocator->malloc(allocator->ctx, size);
}

static void *
calloc_wrapper(void *ctx, size_t nelem, size_t elsize)
{
    PyMemAllocatorEx *allocator = (PyMemAllocatorEx *)ctx;
    return allocator->calloc(allocator->ctx, nelem, elsize);
}

static void *
realloc_wrapper(void *ctx, void *ptr, size_t new_size)
{
    PyMemAllocatorEx *allocator = (PyMemAllocatorEx *)ctx;
    return allocator->realloc(allocator->ctx, ptr, new_size);
}

static void
free_wrapper(void *ctx, void *ptr)
{
    PyMemAllocatorEx *allocator = (PyMemAllocatorEx *)ctx;
    allocator->free(allocator->ctx, ptr);
}

static void
wrap_allocator(PyMemAllocatorEx *allocator)
{
    PyMem_GetAllocator(PYMEM_DOMAIN_OBJ, allocator);
    PyMemAllocatorEx wrapper = {
        .malloc = &malloc_wrapper,
        .calloc = &calloc_wrapper,
        .realloc = &realloc_wrapper,
        .free = &free_wrapper,
        .ctx = allocator,
    };
    PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &wrapper);
}

static void
unwrap_allocator(PyMemAllocatorEx *allocator)
{
    PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, allocator);
}

static int
test_get_incomplete_frame(void)
{
    _testembed_Py_InitializeFromConfig();
    PyMemAllocatorEx allocator;
    wrap_allocator(&allocator);
    // Force an allocation with an incomplete (generator) frame:
    int result = PyRun_SimpleString("(_ for _ in ())");
    unwrap_allocator(&allocator);
    Py_Finalize();
    return result;
}


/* *********************************************************
 * List of test cases and the function that implements it.
 *
 * Names are compared case-sensitively with the first
 * argument. If no match is found, or no first argument was
 * provided, the names of all test cases are printed and
 * the exit code will be -1.
 *
 * The int returned from test functions is used as the exit
 * code, and test_capi treats all non-zero exit codes as a
 * failed test.
 *********************************************************/
struct TestCase
{
    const char *name;
    int (*func)(void);
};

static struct TestCase TestCases[] = {
    // Python initialization
    {"test_repeated_init_exec", test_repeated_init_exec},
    {"test_repeated_simple_init", test_repeated_simple_init},
    {"test_forced_io_encoding", test_forced_io_encoding},
    {"test_repeated_init_and_subinterpreters", test_repeated_init_and_subinterpreters},
    {"test_repeated_init_and_inittab", test_repeated_init_and_inittab},
    {"test_pre_initialization_api", test_pre_initialization_api},
    {"test_pre_initialization_sys_options", test_pre_initialization_sys_options},
    {"test_bpo20891", test_bpo20891},
    {"test_initialize_twice", test_initialize_twice},
    {"test_initialize_pymain", test_initialize_pymain},
    {"test_init_initialize_config", test_init_initialize_config},
    {"test_preinit_compat_config", test_preinit_compat_config},
    {"test_init_compat_config", test_init_compat_config},
    {"test_init_global_config", test_init_global_config},
    {"test_init_from_config", test_init_from_config},
    {"test_init_parse_argv", test_init_parse_argv},
    {"test_init_dont_parse_argv", test_init_dont_parse_argv},
    {"test_init_compat_env", test_init_compat_env},
    {"test_init_python_env", test_init_python_env},
    {"test_init_env_dev_mode", test_init_env_dev_mode},
    {"test_init_env_dev_mode_alloc", test_init_env_dev_mode_alloc},
    {"test_init_dont_configure_locale", test_init_dont_configure_locale},
    {"test_init_dev_mode", test_init_dev_mode},
    {"test_init_isolated_flag", test_init_isolated_flag},
    {"test_preinit_isolated_config", test_preinit_isolated_config},
    {"test_init_isolated_config", test_init_isolated_config},
    {"test_preinit_python_config", test_preinit_python_config},
    {"test_init_python_config", test_init_python_config},
    {"test_preinit_isolated1", test_preinit_isolated1},
    {"test_preinit_isolated2", test_preinit_isolated2},
    {"test_preinit_parse_argv", test_preinit_parse_argv},
    {"test_preinit_dont_parse_argv", test_preinit_dont_parse_argv},
    {"test_init_read_set", test_init_read_set},
    {"test_init_run_main", test_init_run_main},
    {"test_init_main", test_init_main},
    {"test_init_sys_add", test_init_sys_add},
    {"test_init_setpath", test_init_setpath},
    {"test_init_setpath_config", test_init_setpath_config},
    {"test_init_setpythonhome", test_init_setpythonhome},
    {"test_init_is_python_build", test_init_is_python_build},
    {"test_init_warnoptions", test_init_warnoptions},
    {"test_init_set_config", test_init_set_config},
    {"test_run_main", test_run_main},
    {"test_run_main_loop", test_run_main_loop},
    {"test_get_argc_argv", test_get_argc_argv},
    {"test_init_use_frozen_modules", test_init_use_frozen_modules},
    {"test_init_main_interpreter_settings", test_init_main_interpreter_settings},

    // Audit
    {"test_open_code_hook", test_open_code_hook},
    {"test_audit", test_audit},
    {"test_audit_tuple", test_audit_tuple},
    {"test_audit_subinterpreter", test_audit_subinterpreter},
    {"test_audit_run_command", test_audit_run_command},
    {"test_audit_run_file", test_audit_run_file},
    {"test_audit_run_interactivehook", test_audit_run_interactivehook},
    {"test_audit_run_startup", test_audit_run_startup},
    {"test_audit_run_stdin", test_audit_run_stdin},

    // Specific C API
    {"test_unicode_id_init", test_unicode_id_init},
#ifndef MS_WINDOWS
    {"test_frozenmain", test_frozenmain},
#endif
    {"test_get_incomplete_frame", test_get_incomplete_frame},

    {NULL, NULL}
};


int main(int argc, char *argv[])
{
    main_argc = argc;
    main_argv = argv;

    if (argc > 1) {
        for (struct TestCase *tc = TestCases; tc && tc->name; tc++) {
            if (strcmp(argv[1], tc->name) == 0)
                return (*tc->func)();
        }
    }

    /* No match found, or no test name provided, so display usage */
    printf("Python " PY_VERSION " _testembed executable for embedded interpreter tests\n"
           "Normally executed via 'EmbeddingTests' in Lib/test/test_embed.py\n\n"
           "Usage: %s TESTNAME\n\nAll available tests:\n", argv[0]);
    for (struct TestCase *tc = TestCases; tc && tc->name; tc++) {
        printf("  %s\n", tc->name);
    }

    /* Non-zero exit code will cause test_embed.py tests to fail.
       This is intentional. */
    return -1;
}