1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
|
/* Python interpreter main program */
#include "Python.h"
#include "osdefs.h"
#include "internal/import.h"
#include "internal/pygetopt.h"
#include "internal/pystate.h"
#include <locale.h>
#if defined(MS_WINDOWS) || defined(__CYGWIN__)
# include <windows.h>
# ifdef HAVE_IO_H
# include <io.h>
# endif
# ifdef HAVE_FCNTL_H
# include <fcntl.h>
# endif
#endif
#ifdef _MSC_VER
# include <crtdbg.h>
#endif
#ifdef __FreeBSD__
# include <fenv.h>
#endif
#if defined(MS_WINDOWS)
# define PYTHONHOMEHELP "<prefix>\\python{major}{minor}"
#else
# define PYTHONHOMEHELP "<prefix>/lib/pythonX.X"
#endif
#define COPYRIGHT \
"Type \"help\", \"copyright\", \"credits\" or \"license\" " \
"for more information."
#ifdef __cplusplus
extern "C" {
#endif
#define DECODE_LOCALE_ERR(NAME, LEN) \
(((LEN) == -2) \
? _Py_INIT_USER_ERR("cannot decode " NAME) \
: _Py_INIT_NO_MEMORY())
#define SET_DECODE_ERROR(NAME, LEN) \
do { \
if ((LEN) == (size_t)-2) { \
pymain->err = _Py_INIT_USER_ERR("cannot decode " NAME); \
} \
else { \
pymain->err = _Py_INIT_NO_MEMORY(); \
} \
} while (0)
/* For Py_GetArgcArgv(); set by main() */
static wchar_t **orig_argv = NULL;
static int orig_argc = 0;
/* command line options */
#define BASE_OPTS L"bBc:dEhiIJm:OqRsStuvVW:xX:?"
#define PROGRAM_OPTS BASE_OPTS
static const _PyOS_LongOption longoptions[] = {
{L"check-hash-based-pycs", 1, 0},
{NULL, 0, 0},
};
/* Short usage message (with %s for argv0) */
static const char usage_line[] =
"usage: %ls [option] ... [-c cmd | -m mod | file | -] [arg] ...\n";
/* Long usage message, split into parts < 512 bytes */
static const char usage_1[] = "\
Options and arguments (and corresponding environment variables):\n\
-b : issue warnings about str(bytes_instance), str(bytearray_instance)\n\
and comparing bytes/bytearray with str. (-bb: issue errors)\n\
-B : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x\n\
-c cmd : program passed in as string (terminates option list)\n\
-d : debug output from parser; also PYTHONDEBUG=x\n\
-E : ignore PYTHON* environment variables (such as PYTHONPATH)\n\
-h : print this help message and exit (also --help)\n\
";
static const char usage_2[] = "\
-i : inspect interactively after running script; forces a prompt even\n\
if stdin does not appear to be a terminal; also PYTHONINSPECT=x\n\
-I : isolate Python from the user's environment (implies -E and -s)\n\
-m mod : run library module as a script (terminates option list)\n\
-O : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x\n\
-OO : remove doc-strings in addition to the -O optimizations\n\
-q : don't print version and copyright messages on interactive startup\n\
-s : don't add user site directory to sys.path; also PYTHONNOUSERSITE\n\
-S : don't imply 'import site' on initialization\n\
";
static const char usage_3[] = "\
-u : force the stdout and stderr streams to be unbuffered;\n\
this option has no effect on stdin; also PYTHONUNBUFFERED=x\n\
-v : verbose (trace import statements); also PYTHONVERBOSE=x\n\
can be supplied multiple times to increase verbosity\n\
-V : print the Python version number and exit (also --version)\n\
when given twice, print more information about the build\n\
-W arg : warning control; arg is action:message:category:module:lineno\n\
also PYTHONWARNINGS=arg\n\
-x : skip first line of source, allowing use of non-Unix forms of #!cmd\n\
-X opt : set implementation-specific option\n\
--check-hash-based-pycs always|default|never:\n\
control how Python invalidates hash-based .pyc files\n\
";
static const char usage_4[] = "\
file : program read from script file\n\
- : program read from stdin (default; interactive mode if a tty)\n\
arg ...: arguments passed to program in sys.argv[1:]\n\n\
Other environment variables:\n\
PYTHONSTARTUP: file executed on interactive startup (no default)\n\
PYTHONPATH : '%lc'-separated list of directories prefixed to the\n\
default module search path. The result is sys.path.\n\
";
static const char usage_5[] =
"PYTHONHOME : alternate <prefix> directory (or <prefix>%lc<exec_prefix>).\n"
" The default module search path uses %s.\n"
"PYTHONCASEOK : ignore case in 'import' statements (Windows).\n"
"PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.\n"
"PYTHONFAULTHANDLER: dump the Python traceback on fatal errors.\n";
static const char usage_6[] =
"PYTHONHASHSEED: if this variable is set to 'random', a random value is used\n"
" to seed the hashes of str, bytes and datetime objects. It can also be\n"
" set to an integer in the range [0,4294967295] to get hash values with a\n"
" predictable seed.\n"
"PYTHONMALLOC: set the Python memory allocators and/or install debug hooks\n"
" on Python memory allocators. Use PYTHONMALLOC=debug to install debug\n"
" hooks.\n"
"PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the locale\n"
" coercion behavior. Use PYTHONCOERCECLOCALE=warn to request display of\n"
" locale coercion and locale compatibility warnings on stderr.\n"
"PYTHONDEVMODE: enable the development mode.\n";
static void
pymain_usage(int error, const wchar_t* program)
{
FILE *f = error ? stderr : stdout;
fprintf(f, usage_line, program);
if (error)
fprintf(f, "Try `python -h' for more information.\n");
else {
fputs(usage_1, f);
fputs(usage_2, f);
fputs(usage_3, f);
fprintf(f, usage_4, (wint_t)DELIM);
fprintf(f, usage_5, (wint_t)DELIM, PYTHONHOMEHELP);
fputs(usage_6, f);
}
}
static const char*
pymain_get_env_var(const char *name)
{
const char *var = Py_GETENV(name);
if (var && var[0] != '\0') {
return var;
}
else {
return NULL;
}
}
static void
pymain_run_startup(PyCompilerFlags *cf)
{
const char *startup = pymain_get_env_var("PYTHONSTARTUP");
if (startup == NULL) {
return;
}
FILE *fp = _Py_fopen(startup, "r");
if (fp == NULL) {
int save_errno = errno;
PySys_WriteStderr("Could not open PYTHONSTARTUP\n");
errno = save_errno;
PyErr_SetFromErrnoWithFilename(PyExc_OSError,
startup);
PyErr_Print();
PyErr_Clear();
return;
}
(void) PyRun_SimpleFileExFlags(fp, startup, 0, cf);
PyErr_Clear();
fclose(fp);
}
static void
pymain_run_interactive_hook(void)
{
PyObject *sys, *hook, *result;
sys = PyImport_ImportModule("sys");
if (sys == NULL) {
goto error;
}
hook = PyObject_GetAttrString(sys, "__interactivehook__");
Py_DECREF(sys);
if (hook == NULL) {
PyErr_Clear();
return;
}
result = _PyObject_CallNoArg(hook);
Py_DECREF(hook);
if (result == NULL) {
goto error;
}
Py_DECREF(result);
return;
error:
PySys_WriteStderr("Failed calling sys.__interactivehook__\n");
PyErr_Print();
PyErr_Clear();
}
static int
pymain_run_module(wchar_t *modname, int set_argv0)
{
PyObject *module, *runpy, *runmodule, *runargs, *result;
runpy = PyImport_ImportModule("runpy");
if (runpy == NULL) {
fprintf(stderr, "Could not import runpy module\n");
PyErr_Print();
return -1;
}
runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main");
if (runmodule == NULL) {
fprintf(stderr, "Could not access runpy._run_module_as_main\n");
PyErr_Print();
Py_DECREF(runpy);
return -1;
}
module = PyUnicode_FromWideChar(modname, wcslen(modname));
if (module == NULL) {
fprintf(stderr, "Could not convert module name to unicode\n");
PyErr_Print();
Py_DECREF(runpy);
Py_DECREF(runmodule);
return -1;
}
runargs = Py_BuildValue("(Oi)", module, set_argv0);
if (runargs == NULL) {
fprintf(stderr,
"Could not create arguments for runpy._run_module_as_main\n");
PyErr_Print();
Py_DECREF(runpy);
Py_DECREF(runmodule);
Py_DECREF(module);
return -1;
}
result = PyObject_Call(runmodule, runargs, NULL);
if (result == NULL) {
PyErr_Print();
}
Py_DECREF(runpy);
Py_DECREF(runmodule);
Py_DECREF(module);
Py_DECREF(runargs);
if (result == NULL) {
return -1;
}
Py_DECREF(result);
return 0;
}
static PyObject *
pymain_get_importer(wchar_t *filename)
{
PyObject *sys_path0 = NULL, *importer;
sys_path0 = PyUnicode_FromWideChar(filename, wcslen(filename));
if (sys_path0 == NULL) {
goto error;
}
importer = PyImport_GetImporter(sys_path0);
if (importer == NULL) {
goto error;
}
if (importer == Py_None) {
Py_DECREF(sys_path0);
Py_DECREF(importer);
return NULL;
}
Py_DECREF(importer);
return sys_path0;
error:
Py_XDECREF(sys_path0);
PySys_WriteStderr("Failed checking if argv[0] is an import path entry\n");
PyErr_Print();
PyErr_Clear();
return NULL;
}
static int
pymain_run_command(wchar_t *command, PyCompilerFlags *cf)
{
PyObject *unicode, *bytes;
int ret;
unicode = PyUnicode_FromWideChar(command, -1);
if (unicode == NULL) {
goto error;
}
bytes = PyUnicode_AsUTF8String(unicode);
Py_DECREF(unicode);
if (bytes == NULL) {
goto error;
}
ret = PyRun_SimpleStringFlags(PyBytes_AsString(bytes), cf);
Py_DECREF(bytes);
return (ret != 0);
error:
PySys_WriteStderr("Unable to decode the command from the command line:\n");
PyErr_Print();
return 1;
}
static int
pymain_run_file(FILE *fp, const wchar_t *filename, PyCompilerFlags *p_cf)
{
PyObject *unicode, *bytes = NULL;
const char *filename_str;
int run;
/* call pending calls like signal handlers (SIGINT) */
if (Py_MakePendingCalls() == -1) {
PyErr_Print();
return 1;
}
if (filename) {
unicode = PyUnicode_FromWideChar(filename, wcslen(filename));
if (unicode != NULL) {
bytes = PyUnicode_EncodeFSDefault(unicode);
Py_DECREF(unicode);
}
if (bytes != NULL) {
filename_str = PyBytes_AsString(bytes);
}
else {
PyErr_Clear();
filename_str = "<encoding error>";
}
}
else {
filename_str = "<stdin>";
}
run = PyRun_AnyFileExFlags(fp, filename_str, filename != NULL, p_cf);
Py_XDECREF(bytes);
return run != 0;
}
/* Main program */
typedef struct {
size_t len;
wchar_t **options;
} _Py_OptList;
typedef struct {
wchar_t *filename; /* Trailing arg without -c or -m */
wchar_t *command; /* -c argument */
wchar_t *module; /* -m argument */
_Py_OptList warning_options; /* -W options */
int print_help; /* -h, -? options */
int print_version; /* -V option */
int bytes_warning; /* Py_BytesWarningFlag, -b */
int debug; /* Py_DebugFlag, -b, PYTHONDEBUG */
int inspect; /* Py_InspectFlag, -i, PYTHONINSPECT */
int interactive; /* Py_InteractiveFlag, -i */
int isolated; /* Py_IsolatedFlag, -I */
int optimization_level; /* Py_OptimizeFlag, -O, PYTHONOPTIMIZE */
int dont_write_bytecode; /* Py_DontWriteBytecodeFlag, -B, PYTHONDONTWRITEBYTECODE */
int no_user_site_directory; /* Py_NoUserSiteDirectory, -I, -s, PYTHONNOUSERSITE */
int no_site_import; /* Py_NoSiteFlag, -S */
int use_unbuffered_io; /* Py_UnbufferedStdioFlag, -u, PYTHONUNBUFFERED */
int verbosity; /* Py_VerboseFlag, -v, PYTHONVERBOSE */
int quiet_flag; /* Py_QuietFlag, -q */
int skip_first_line; /* -x option */
_Py_OptList xoptions; /* -X options */
const char *check_hash_pycs_mode; /* --check-hash-based-pycs */
#ifdef MS_WINDOWS
int legacy_windows_fs_encoding; /* Py_LegacyWindowsFSEncodingFlag,
PYTHONLEGACYWINDOWSFSENCODING */
int legacy_windows_stdio; /* Py_LegacyWindowsStdioFlag,
PYTHONLEGACYWINDOWSSTDIO */
#endif
} _Py_CommandLineDetails;
/* Structure used by Py_Main() to pass data to subfunctions */
typedef struct {
/* Exit status ("exit code") */
int status;
PyCompilerFlags cf;
/* non-zero is stdin is a TTY or if -i option is used */
int stdin_is_interactive;
_PyCoreConfig core_config;
_PyMainInterpreterConfig config;
_Py_CommandLineDetails cmdline;
PyObject *main_importer_path;
/* non-zero if filename, command (-c) or module (-m) is set
on the command line */
int run_code;
/* Error message if a function failed */
_PyInitError err;
/* PYTHONWARNINGS env var */
_Py_OptList env_warning_options;
int argc;
wchar_t **argv;
int use_bytes_argv;
char **bytes_argv;
int sys_argc;
wchar_t **sys_argv;
} _PyMain;
/* .cmdline is initialized to zeros */
#define _PyMain_INIT \
{.core_config = _PyCoreConfig_INIT, \
.config = _PyMainInterpreterConfig_INIT, \
.run_code = -1, \
.err = _Py_INIT_OK()}
/* Note: _PyMain_INIT sets other fields to 0/NULL */
static void
pymain_optlist_clear(_Py_OptList *list)
{
for (size_t i=0; i < list->len; i++) {
PyMem_RawFree(list->options[i]);
}
PyMem_RawFree(list->options);
list->len = 0;
list->options = NULL;
}
/* Free global variables which cannot be freed in Py_Finalize():
configuration options set before Py_Initialize() which should
remain valid after Py_Finalize(), since Py_Initialize()/Py_Finalize() can
be called multiple times.
Called with the current memory allocators. */
static void
pymain_free_globals(_PyMain *pymain)
{
_PyPathConfig_Clear(&_Py_path_config);
_PyImport_Fini2();
#ifdef __INSURE__
/* Insure++ is a memory analysis tool that aids in discovering
* memory leaks and other memory problems. On Python exit, the
* interned string dictionaries are flagged as being in use at exit
* (which it is). Under normal circumstances, this is fine because
* the memory will be automatically reclaimed by the system. Under
* memory debugging, it's a huge source of useless noise, so we
* trade off slower shutdown for less distraction in the memory
* reports. -baw
*/
_Py_ReleaseInternedUnicodeStrings();
#endif /* __INSURE__ */
}
/* Clear argv allocated by pymain_decode_bytes_argv() */
static void
pymain_clear_bytes_argv(_PyMain *pymain, int argc)
{
if (pymain->use_bytes_argv && pymain->argv != NULL) {
for (int i = 0; i < argc; i++) {
PyMem_RawFree(pymain->argv[i]);
}
PyMem_RawFree(pymain->argv);
pymain->argv = NULL;
}
}
static int
pymain_decode_bytes_argv(_PyMain *pymain)
{
assert(pymain->argv == NULL);
/* +1 for a the NULL terminator */
size_t size = sizeof(wchar_t*) * (pymain->argc + 1);
pymain->argv = (wchar_t **)PyMem_RawMalloc(size);
if (pymain->argv == NULL) {
pymain->err = _Py_INIT_NO_MEMORY();
return -1;
}
for (int i = 0; i < pymain->argc; i++) {
size_t len;
pymain->argv[i] = Py_DecodeLocale(pymain->bytes_argv[i], &len);
if (pymain->argv[i] == NULL) {
pymain_clear_bytes_argv(pymain, i);
pymain->err = DECODE_LOCALE_ERR("command line arguments",
(Py_ssize_t)len);
return -1;
}
}
pymain->argv[pymain->argc] = NULL;
return 0;
}
static void
pymain_clear_pymain(_PyMain *pymain)
{
_Py_CommandLineDetails *cmdline = &pymain->cmdline;
pymain_optlist_clear(&cmdline->warning_options);
pymain_optlist_clear(&cmdline->xoptions);
PyMem_RawFree(cmdline->command);
cmdline->command = NULL;
PyMem_RawFree(pymain->sys_argv);
pymain->sys_argv = NULL;
pymain_optlist_clear(&pymain->env_warning_options);
pymain_clear_bytes_argv(pymain, pymain->argc);
_PyCoreConfig_Clear(&pymain->core_config);
}
/* Clear Python ojects */
static void
pymain_clear_python(_PyMain *pymain)
{
Py_CLEAR(pymain->main_importer_path);
_PyMainInterpreterConfig_Clear(&pymain->config);
}
static void
pymain_free(_PyMain *pymain)
{
/* Force the allocator used by pymain_read_conf() */
PyMemAllocatorEx old_alloc;
_PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
pymain_clear_python(pymain);
pymain_clear_pymain(pymain);
pymain_free_globals(pymain);
PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
}
static int
pymain_run_main_from_importer(_PyMain *pymain)
{
/* Assume sys_path0 has already been checked by pymain_get_importer(),
* so put it in sys.path[0] and import __main__ */
PyObject *sys_path = PySys_GetObject("path");
if (sys_path == NULL) {
PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path");
goto error;
}
if (PyList_Insert(sys_path, 0, pymain->main_importer_path)) {
goto error;
}
int sts = pymain_run_module(L"__main__", 0);
return (sts != 0);
error:
Py_CLEAR(pymain->main_importer_path);
PyErr_Print();
return 1;
}
static wchar_t*
pymain_wstrdup(_PyMain *pymain, const wchar_t *str)
{
wchar_t *str2 = _PyMem_RawWcsdup(str);
if (str2 == NULL) {
pymain->err = _Py_INIT_NO_MEMORY();
return NULL;
}
return str2;
}
static int
pymain_optlist_append(_PyMain *pymain, _Py_OptList *list, const wchar_t *str)
{
wchar_t *str2 = pymain_wstrdup(pymain, str);
if (str2 == NULL) {
return -1;
}
size_t size = (list->len + 1) * sizeof(list[0]);
wchar_t **options2 = (wchar_t **)PyMem_RawRealloc(list->options, size);
if (options2 == NULL) {
PyMem_RawFree(str2);
pymain->err = _Py_INIT_NO_MEMORY();
return -1;
}
options2[list->len] = str2;
list->options = options2;
list->len++;
return 0;
}
/* Parse the command line arguments
Return 0 on success.
Return 1 if parsing failed.
Set pymain->err and return -1 on other errors. */
static int
pymain_parse_cmdline_impl(_PyMain *pymain)
{
_Py_CommandLineDetails *cmdline = &pymain->cmdline;
_PyOS_ResetGetOpt();
do {
int longindex = -1;
int c = _PyOS_GetOpt(pymain->argc, pymain->argv, PROGRAM_OPTS,
longoptions, &longindex);
if (c == EOF) {
break;
}
if (c == 'c') {
/* -c is the last option; following arguments
that look like options are left for the
command to interpret. */
size_t len = wcslen(_PyOS_optarg) + 1 + 1;
wchar_t *command = PyMem_RawMalloc(sizeof(wchar_t) * len);
if (command == NULL) {
pymain->err = _Py_INIT_NO_MEMORY();
return -1;
}
memcpy(command, _PyOS_optarg, len * sizeof(wchar_t));
command[len - 2] = '\n';
command[len - 1] = 0;
cmdline->command = command;
break;
}
if (c == 'm') {
/* -m is the last option; following arguments
that look like options are left for the
module to interpret. */
cmdline->module = _PyOS_optarg;
break;
}
switch (c) {
case 0:
// Handle long option.
assert(longindex == 0); // Only one long option now.
if (!wcscmp(_PyOS_optarg, L"always")) {
cmdline->check_hash_pycs_mode = "always";
} else if (!wcscmp(_PyOS_optarg, L"never")) {
cmdline->check_hash_pycs_mode = "never";
} else if (!wcscmp(_PyOS_optarg, L"default")) {
cmdline->check_hash_pycs_mode = "default";
} else {
fprintf(stderr, "--check-hash-based-pycs must be one of "
"'default', 'always', or 'never'\n");
return 1;
}
break;
case 'b':
cmdline->bytes_warning++;
break;
case 'd':
cmdline->debug++;
break;
case 'i':
cmdline->inspect++;
cmdline->interactive++;
break;
case 'I':
pymain->core_config.ignore_environment++;
cmdline->isolated++;
cmdline->no_user_site_directory++;
break;
/* case 'J': reserved for Jython */
case 'O':
cmdline->optimization_level++;
break;
case 'B':
cmdline->dont_write_bytecode++;
break;
case 's':
cmdline->no_user_site_directory++;
break;
case 'S':
cmdline->no_site_import++;
break;
case 'E':
pymain->core_config.ignore_environment++;
break;
case 't':
/* ignored for backwards compatibility */
break;
case 'u':
cmdline->use_unbuffered_io = 1;
break;
case 'v':
cmdline->verbosity++;
break;
case 'x':
cmdline->skip_first_line = 1;
break;
case 'h':
case '?':
cmdline->print_help++;
break;
case 'V':
cmdline->print_version++;
break;
case 'W':
if (pymain_optlist_append(pymain, &cmdline->warning_options,
_PyOS_optarg) < 0) {
return -1;
}
break;
case 'X':
if (pymain_optlist_append(pymain, &cmdline->xoptions,
_PyOS_optarg) < 0) {
return -1;
}
break;
case 'q':
cmdline->quiet_flag++;
break;
case 'R':
pymain->core_config.use_hash_seed = 0;
break;
/* This space reserved for other options */
default:
/* unknown argument: parsing failed */
return 1;
}
} while (1);
if (cmdline->command == NULL && cmdline->module == NULL
&& _PyOS_optind < pymain->argc
&& wcscmp(pymain->argv[_PyOS_optind], L"-") != 0)
{
cmdline->filename = pymain->argv[_PyOS_optind];
}
pymain->run_code = (cmdline->command != NULL || cmdline->filename != NULL
|| cmdline->module != NULL);
/* -c and -m options are exclusive */
assert(!(cmdline->command != NULL && cmdline->module != NULL));
return 0;
}
static int
pymain_add_xoption(PyObject *opts, const wchar_t *s)
{
PyObject *name, *value;
const wchar_t *name_end = wcschr(s, L'=');
if (!name_end) {
name = PyUnicode_FromWideChar(s, -1);
value = Py_True;
Py_INCREF(value);
}
else {
name = PyUnicode_FromWideChar(s, name_end - s);
value = PyUnicode_FromWideChar(name_end + 1, -1);
}
if (name == NULL || value == NULL) {
goto error;
}
if (PyDict_SetItem(opts, name, value) < 0) {
goto error;
}
Py_DECREF(name);
Py_DECREF(value);
return 0;
error:
Py_XDECREF(name);
Py_XDECREF(value);
return -1;
}
static int
pymain_init_xoptions_dict(_PyMain *pymain)
{
_Py_OptList *options = &pymain->cmdline.xoptions;
PyObject *dict = PyDict_New();
if (dict == NULL) {
return -1;
}
for (size_t i=0; i < options->len; i++) {
wchar_t *option = options->options[i];
if (pymain_add_xoption(dict, option) < 0) {
Py_DECREF(dict);
return -1;
}
}
pymain->config.xoptions = dict;
return 0;
}
static int
pymain_add_warnings_optlist(PyObject *warnoptions, _Py_OptList *warnings)
{
for (size_t i = 0; i < warnings->len; i++) {
PyObject *option = PyUnicode_FromWideChar(warnings->options[i], -1);
if (option == NULL) {
return -1;
}
if (PyList_Append(warnoptions, option)) {
Py_DECREF(option);
return -1;
}
Py_DECREF(option);
}
return 0;
}
static int
pymain_add_warning_dev_mode(PyObject *warnoptions, _PyCoreConfig *core_config)
{
if (core_config->dev_mode) {
PyObject *option = PyUnicode_FromString("default");
if (option == NULL) {
return -1;
}
if (PyList_Append(warnoptions, option)) {
Py_DECREF(option);
return -1;
}
Py_DECREF(option);
}
return 0;
}
static int
pymain_add_warning_bytes_flag(PyObject *warnoptions, int bytes_warning_flag)
{
/* If the bytes_warning_flag isn't set, bytesobject.c and bytearrayobject.c
* don't even try to emit a warning, so we skip setting the filter in that
* case.
*/
if (!bytes_warning_flag) {
return 0;
}
const char *filter = (bytes_warning_flag > 1) ? "error::BytesWarning":
"default::BytesWarning";
PyObject *option = PyUnicode_FromString(filter);
if (option == NULL) {
return -1;
}
if (PyList_Append(warnoptions, option)) {
Py_DECREF(option);
return -1;
}
Py_DECREF(option);
return 0;
}
static int
pymain_init_warnoptions(_PyMain *pymain)
{
PyObject *warnoptions = PyList_New(0);
if (warnoptions == NULL) {
return -1;
}
/* The priority order for warnings configuration is (highest precedence
* first):
*
* - the BytesWarning filter, if needed ('-b', '-bb')
* - any '-W' command line options; then
* - the 'PYTHONWARNINGS' environment variable; then
* - the dev mode filter ('-X dev', 'PYTHONDEVMODE'); then
* - any implicit filters added by _warnings.c/warnings.py
*
* All settings except the last are passed to the warnings module via
* the `sys.warnoptions` list. Since the warnings module works on the basis
* of "the most recently added filter will be checked first", we add
* the lowest precedence entries first so that later entries override them.
*/
if (pymain_add_warning_dev_mode(warnoptions, &pymain->core_config) < 0) {
goto error;
}
if (pymain_add_warnings_optlist(warnoptions, &pymain->env_warning_options) < 0) {
goto error;
}
if (pymain_add_warnings_optlist(warnoptions, &pymain->cmdline.warning_options) < 0) {
goto error;
}
if (pymain_add_warning_bytes_flag(warnoptions, pymain->cmdline.bytes_warning) < 0) {
goto error;
}
pymain->config.warnoptions = warnoptions;
return 0;
error:
Py_DECREF(warnoptions);
return -1;
}
/* Get warning options from PYTHONWARNINGS environment variable.
Return 0 on success.
Set pymain->err and return -1 on error. */
static int
pymain_warnings_envvar(_PyMain *pymain)
{
if (Py_IgnoreEnvironmentFlag) {
return 0;
}
#ifdef MS_WINDOWS
const wchar_t *wp;
if ((wp = _wgetenv(L"PYTHONWARNINGS")) && *wp != L'\0') {
wchar_t *warning, *context = NULL;
wchar_t *buf = pymain_wstrdup(pymain, wp);
if (buf == NULL) {
return -1;
}
for (warning = wcstok_s(buf, L",", &context);
warning != NULL;
warning = wcstok_s(NULL, L",", &context)) {
if (pymain_optlist_append(pymain, &pymain->env_warning_options,
warning) < 0) {
PyMem_RawFree(buf);
return -1;
}
}
PyMem_RawFree(buf);
}
#else
const char *p = pymain_get_env_var("PYTHONWARNINGS");
if (p != NULL) {
char *buf, *oldloc;
/* settle for strtok here as there's no one standard
C89 wcstok */
buf = (char *)PyMem_RawMalloc(strlen(p) + 1);
if (buf == NULL) {
pymain->err = _Py_INIT_NO_MEMORY();
return -1;
}
strcpy(buf, p);
oldloc = _PyMem_RawStrdup(setlocale(LC_ALL, NULL));
setlocale(LC_ALL, "");
for (p = strtok(buf, ","); p != NULL; p = strtok(NULL, ",")) {
size_t len;
wchar_t *warning = Py_DecodeLocale(p, &len);
if (warning == NULL) {
SET_DECODE_ERROR("PYTHONWARNINGS environment variable", len);
return -1;
}
if (pymain_optlist_append(pymain, &pymain->env_warning_options,
warning) < 0) {
PyMem_RawFree(warning);
return -1;
}
PyMem_RawFree(warning);
}
setlocale(LC_ALL, oldloc);
PyMem_RawFree(oldloc);
PyMem_RawFree(buf);
}
#endif
return 0;
}
static void
pymain_init_stdio(_PyMain *pymain)
{
pymain->stdin_is_interactive = (isatty(fileno(stdin))
|| Py_InteractiveFlag);
#if defined(MS_WINDOWS) || defined(__CYGWIN__)
/* don't translate newlines (\r\n <=> \n) */
_setmode(fileno(stdin), O_BINARY);
_setmode(fileno(stdout), O_BINARY);
_setmode(fileno(stderr), O_BINARY);
#endif
if (Py_UnbufferedStdioFlag) {
#ifdef HAVE_SETVBUF
setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ);
setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
#else /* !HAVE_SETVBUF */
setbuf(stdin, (char *)NULL);
setbuf(stdout, (char *)NULL);
setbuf(stderr, (char *)NULL);
#endif /* !HAVE_SETVBUF */
}
else if (Py_InteractiveFlag) {
#ifdef MS_WINDOWS
/* Doesn't have to have line-buffered -- use unbuffered */
/* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
#else /* !MS_WINDOWS */
#ifdef HAVE_SETVBUF
setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ);
setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
#endif /* HAVE_SETVBUF */
#endif /* !MS_WINDOWS */
/* Leave stderr alone - it should be unbuffered anyway. */
}
}
/* Get the program name: use PYTHONEXECUTABLE and __PYVENV_LAUNCHER__
environment variables on macOS if available. */
static _PyInitError
config_get_program_name(_PyCoreConfig *config)
{
assert(config->program_name == NULL);
/* If Py_SetProgramName() was called, use its value */
const wchar_t *program_name = _Py_path_config.program_name;
if (program_name != NULL) {
config->program_name = _PyMem_RawWcsdup(program_name);
if (config->program_name == NULL) {
return _Py_INIT_NO_MEMORY();
}
}
#ifdef __APPLE__
/* On MacOS X, when the Python interpreter is embedded in an
application bundle, it gets executed by a bootstrapping script
that does os.execve() with an argv[0] that's different from the
actual Python executable. This is needed to keep the Finder happy,
or rather, to work around Apple's overly strict requirements of
the process name. However, we still need a usable sys.executable,
so the actual executable path is passed in an environment variable.
See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
script. */
const char *p = pymain_get_env_var("PYTHONEXECUTABLE");
if (p != NULL) {
size_t len;
wchar_t* program_name = Py_DecodeLocale(p, &len);
if (program_name == NULL) {
return DECODE_LOCALE_ERR("PYTHONEXECUTABLE environment "
"variable", (Py_ssize_t)len);
}
config->program_name = program_name;
}
#ifdef WITH_NEXT_FRAMEWORK
else {
const char* pyvenv_launcher = getenv("__PYVENV_LAUNCHER__");
if (pyvenv_launcher && *pyvenv_launcher) {
/* Used by Mac/Tools/pythonw.c to forward
* the argv0 of the stub executable
*/
size_t len;
wchar_t* program_name = Py_DecodeLocale(pyvenv_launcher, &len);
if (program_name == NULL) {
return DECODE_LOCALE_ERR("__PYVENV_LAUNCHER__ environment "
"variable", (Py_ssize_t)len);
}
config->program_name = program_name;
}
}
#endif /* WITH_NEXT_FRAMEWORK */
#endif /* __APPLE__ */
return _Py_INIT_OK();
}
/* If config_get_program_name() found no program name: use argv[0] by default.
Return 0 on success. Set pymain->err and return -1 on error. */
static int
pymain_get_program_name(_PyMain *pymain)
{
if (pymain->core_config.program_name == NULL) {
/* Use argv[0] by default */
pymain->core_config.program_name = pymain_wstrdup(pymain, pymain->argv[0]);
if (pymain->core_config.program_name == NULL) {
return -1;
}
}
return 0;
}
/* Initialize the main interpreter.
*
* Replaces previous call to Py_Initialize()
*
* Return 0 on success.
* Set pymain->err and return -1 on error.
*/
static int
pymain_init_main_interpreter(_PyMain *pymain)
{
_PyInitError err;
err = _Py_InitializeMainInterpreter(&pymain->config);
if (_Py_INIT_FAILED(err)) {
pymain->err = err;
return -1;
}
return 0;
}
static void
pymain_header(_PyMain *pymain)
{
/* TODO: Move this to _PyRun_PrepareMain */
if (Py_QuietFlag) {
return;
}
if (!Py_VerboseFlag && (pymain->run_code || !pymain->stdin_is_interactive)) {
return;
}
fprintf(stderr, "Python %s on %s\n", Py_GetVersion(), Py_GetPlatform());
if (!Py_NoSiteFlag) {
fprintf(stderr, "%s\n", COPYRIGHT);
}
}
static int
pymain_init_argv(_PyMain *pymain)
{
int argc = pymain->sys_argc;
wchar_t** argv = pymain->sys_argv;
if (argc <= 0 || pymain->sys_argv == NULL) {
/* Ensure at least one (empty) argument is seen */
static wchar_t *empty_argv[1] = {L""};
argv = empty_argv;
argc = 1;
}
PyObject *list = PyList_New(argc);
if (list == NULL) {
return -1;
}
for (int i = 0; i < argc; i++) {
PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
if (v == NULL) {
Py_DECREF(list);
return -1;
}
PyList_SET_ITEM(list, i, v);
}
pymain->config.argv = list;
return 0;
}
static int
pymain_init_sys_argv(_PyMain *pymain)
{
_Py_CommandLineDetails *cmdline = &pymain->cmdline;
if (cmdline->command != NULL || cmdline->module != NULL) {
/* Backup _PyOS_optind */
_PyOS_optind--;
}
/* Copy argv to be able to modify it (to force -c/-m) */
pymain->sys_argc = pymain->argc - _PyOS_optind;
size_t size = pymain->sys_argc * sizeof(pymain->argv[0]);
pymain->sys_argv = PyMem_RawMalloc(size);
if (pymain->sys_argv == NULL) {
pymain->err = _Py_INIT_NO_MEMORY();
return -1;
}
memcpy(pymain->sys_argv, &pymain->argv[_PyOS_optind], size);
if (cmdline->command != NULL) {
/* Force sys.argv[0] = '-c' */
pymain->sys_argv[0] = L"-c";
}
else if (cmdline->module != NULL) {
/* Force sys.argv[0] = '-m'*/
pymain->sys_argv[0] = L"-m";
}
return 0;
}
static int
pymain_update_sys_path(_PyMain *pymain)
{
if (pymain->main_importer_path != NULL) {
/* Let pymain_run_main_from_importer() adjust sys.path[0] later */
return 0;
}
if (Py_IsolatedFlag) {
return 0;
}
/* Prepend argv[0] to sys.path.
If argv[0] is a symlink, use the real path. */
PyObject *sys_path = PySys_GetObject("path");
if (sys_path == NULL) {
pymain->err = _Py_INIT_ERR("can't get sys.path");
return -1;
}
PyObject *path0 = _PyPathConfig_ComputeArgv0(pymain->sys_argc, pymain->sys_argv);
if (path0 == NULL) {
pymain->err = _Py_INIT_NO_MEMORY();
return -1;
}
/* Prepend path0 to sys.path */
if (PyList_Insert(sys_path, 0, path0) < 0) {
Py_DECREF(path0);
pymain->err = _Py_INIT_ERR("sys.path.insert(0, path0) failed");
return -1;
}
Py_DECREF(path0);
return 0;
}
/* Get Py_xxx global configuration variables */
static void
pymain_get_global_config(_PyMain *pymain)
{
_Py_CommandLineDetails *cmdline = &pymain->cmdline;
cmdline->bytes_warning = Py_BytesWarningFlag;
cmdline->debug = Py_DebugFlag;
cmdline->inspect = Py_InspectFlag;
cmdline->interactive = Py_InteractiveFlag;
cmdline->isolated = Py_IsolatedFlag;
cmdline->optimization_level = Py_OptimizeFlag;
cmdline->dont_write_bytecode = Py_DontWriteBytecodeFlag;
cmdline->no_user_site_directory = Py_NoUserSiteDirectory;
cmdline->no_site_import = Py_NoSiteFlag;
cmdline->use_unbuffered_io = Py_UnbufferedStdioFlag;
cmdline->verbosity = Py_VerboseFlag;
cmdline->quiet_flag = Py_QuietFlag;
#ifdef MS_WINDOWS
cmdline->legacy_windows_fs_encoding = Py_LegacyWindowsFSEncodingFlag;
cmdline->legacy_windows_stdio = Py_LegacyWindowsStdioFlag;
#endif
cmdline->check_hash_pycs_mode = _Py_CheckHashBasedPycsMode ;
pymain->core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
pymain->core_config.utf8_mode = Py_UTF8Mode;
}
/* Set Py_XXX global configuration variables */
static void
pymain_set_global_config(_PyMain *pymain)
{
_Py_CommandLineDetails *cmdline = &pymain->cmdline;
Py_BytesWarningFlag = cmdline->bytes_warning;
Py_DebugFlag = cmdline->debug;
Py_InspectFlag = cmdline->inspect;
Py_InteractiveFlag = cmdline->interactive;
Py_IsolatedFlag = cmdline->isolated;
Py_OptimizeFlag = cmdline->optimization_level;
Py_DontWriteBytecodeFlag = cmdline->dont_write_bytecode;
Py_NoUserSiteDirectory = cmdline->no_user_site_directory;
Py_NoSiteFlag = cmdline->no_site_import;
Py_UnbufferedStdioFlag = cmdline->use_unbuffered_io;
Py_VerboseFlag = cmdline->verbosity;
Py_QuietFlag = cmdline->quiet_flag;
_Py_CheckHashBasedPycsMode = cmdline->check_hash_pycs_mode;
#ifdef MS_WINDOWS
Py_LegacyWindowsFSEncodingFlag = cmdline->legacy_windows_fs_encoding;
Py_LegacyWindowsStdioFlag = cmdline->legacy_windows_stdio;
#endif
Py_IgnoreEnvironmentFlag = pymain->core_config.ignore_environment;
Py_UTF8Mode = pymain->core_config.utf8_mode;
/* Random or non-zero hash seed */
Py_HashRandomizationFlag = (pymain->core_config.use_hash_seed == 0 ||
pymain->core_config.hash_seed != 0);
}
static void
pymain_import_readline(_PyMain *pymain)
{
if (Py_IsolatedFlag) {
return;
}
if (!Py_InspectFlag && pymain->run_code) {
return;
}
if (!isatty(fileno(stdin))) {
return;
}
PyObject *mod = PyImport_ImportModule("readline");
if (mod == NULL) {
PyErr_Clear();
}
else {
Py_DECREF(mod);
}
}
static FILE*
pymain_open_filename(_PyMain *pymain)
{
_Py_CommandLineDetails *cmdline = &pymain->cmdline;
FILE* fp;
fp = _Py_wfopen(cmdline->filename, L"r");
if (fp == NULL) {
char *cfilename_buffer;
const char *cfilename;
int err = errno;
cfilename_buffer = Py_EncodeLocale(cmdline->filename, NULL);
if (cfilename_buffer != NULL)
cfilename = cfilename_buffer;
else
cfilename = "<unprintable file name>";
fprintf(stderr, "%ls: can't open file '%s': [Errno %d] %s\n",
pymain->argv[0], cfilename, err, strerror(err));
PyMem_Free(cfilename_buffer);
pymain->status = 2;
return NULL;
}
if (cmdline->skip_first_line) {
int ch;
/* Push back first newline so line numbers
remain the same */
while ((ch = getc(fp)) != EOF) {
if (ch == '\n') {
(void)ungetc(ch, fp);
break;
}
}
}
struct _Py_stat_struct sb;
if (_Py_fstat_noraise(fileno(fp), &sb) == 0 &&
S_ISDIR(sb.st_mode)) {
fprintf(stderr,
"%ls: '%ls' is a directory, cannot continue\n",
pymain->argv[0], cmdline->filename);
fclose(fp);
pymain->status = 1;
return NULL;
}
return fp;
}
static void
pymain_run_filename(_PyMain *pymain)
{
_Py_CommandLineDetails *cmdline = &pymain->cmdline;
if (cmdline->filename == NULL && pymain->stdin_is_interactive) {
Py_InspectFlag = 0; /* do exit on SystemExit */
pymain_run_startup(&pymain->cf);
pymain_run_interactive_hook();
}
if (pymain->main_importer_path != NULL) {
pymain->status = pymain_run_main_from_importer(pymain);
return;
}
FILE *fp;
if (cmdline->filename != NULL) {
fp = pymain_open_filename(pymain);
if (fp == NULL) {
return;
}
}
else {
fp = stdin;
}
pymain->status = pymain_run_file(fp, cmdline->filename, &pymain->cf);
}
static void
pymain_repl(_PyMain *pymain)
{
/* Check this environment variable at the end, to give programs the
opportunity to set it from Python. */
if (!Py_InspectFlag && pymain_get_env_var("PYTHONINSPECT")) {
Py_InspectFlag = 1;
}
if (!(Py_InspectFlag && pymain->stdin_is_interactive
&& pymain->run_code)) {
return;
}
Py_InspectFlag = 0;
pymain_run_interactive_hook();
int res = PyRun_AnyFileFlags(stdin, "<stdin>", &pymain->cf);
pymain->status = (res != 0);
}
/* Parse the command line.
Handle --version and --help options directly.
Return 1 if Python must exit.
Return 0 on success.
Set pymain->err and return -1 on failure. */
static int
pymain_parse_cmdline(_PyMain *pymain)
{
int res = pymain_parse_cmdline_impl(pymain);
if (res < 0) {
return -1;
}
if (res) {
pymain_usage(1, pymain->argv[0]);
pymain->status = 2;
return 1;
}
return 0;
}
static const wchar_t*
pymain_get_xoption(_PyMain *pymain, wchar_t *name)
{
_Py_OptList *list = &pymain->cmdline.xoptions;
for (size_t i=0; i < list->len; i++) {
wchar_t *option = list->options[i];
size_t len;
wchar_t *sep = wcschr(option, L'=');
if (sep != NULL) {
len = (sep - option);
}
else {
len = wcslen(option);
}
if (wcsncmp(option, name, len) == 0 && name[len] == L'\0') {
return option;
}
}
return NULL;
}
static int
pymain_str_to_int(const char *str, int *result)
{
errno = 0;
const char *endptr = str;
long value = strtol(str, (char **)&endptr, 10);
if (*endptr != '\0' || errno == ERANGE) {
return -1;
}
if (value < INT_MIN || value > INT_MAX) {
return -1;
}
*result = (int)value;
return 0;
}
static int
pymain_wstr_to_int(const wchar_t *wstr, int *result)
{
errno = 0;
const wchar_t *endptr = wstr;
long value = wcstol(wstr, (wchar_t **)&endptr, 10);
if (*endptr != '\0' || errno == ERANGE) {
return -1;
}
if (value < INT_MIN || value > INT_MAX) {
return -1;
}
*result = (int)value;
return 0;
}
static int
pymain_init_tracemalloc(_PyMain *pymain)
{
int nframe;
int valid;
const char *env = pymain_get_env_var("PYTHONTRACEMALLOC");
if (env) {
if (!pymain_str_to_int(env, &nframe)) {
valid = (nframe >= 1);
}
else {
valid = 0;
}
if (!valid) {
pymain->err = _Py_INIT_USER_ERR("PYTHONTRACEMALLOC: invalid "
"number of frames");
return -1;
}
pymain->core_config.tracemalloc = nframe;
}
const wchar_t *xoption = pymain_get_xoption(pymain, L"tracemalloc");
if (xoption) {
const wchar_t *sep = wcschr(xoption, L'=');
if (sep) {
if (!pymain_wstr_to_int(sep + 1, &nframe)) {
valid = (nframe >= 1);
}
else {
valid = 0;
}
if (!valid) {
pymain->err = _Py_INIT_USER_ERR("-X tracemalloc=NFRAME: "
"invalid number of frames");
return -1;
}
}
else {
/* -X tracemalloc behaves as -X tracemalloc=1 */
nframe = 1;
}
pymain->core_config.tracemalloc = nframe;
}
return 0;
}
static void
pymain_set_flag_from_env(int *flag, const char *name)
{
const char *var = pymain_get_env_var(name);
if (!var) {
return;
}
int value;
if (pymain_str_to_int(var, &value) < 0 || value < 0) {
/* PYTHONDEBUG=text and PYTHONDEBUG=-2 behave as PYTHONDEBUG=1 */
value = 1;
}
if (*flag < value) {
*flag = value;
}
}
static void
pymain_set_flags_from_env(_PyMain *pymain)
{
_Py_CommandLineDetails *cmdline = &pymain->cmdline;
pymain_set_flag_from_env(&cmdline->debug,
"PYTHONDEBUG");
pymain_set_flag_from_env(&cmdline->verbosity,
"PYTHONVERBOSE");
pymain_set_flag_from_env(&cmdline->optimization_level,
"PYTHONOPTIMIZE");
pymain_set_flag_from_env(&cmdline->inspect,
"PYTHONINSPECT");
pymain_set_flag_from_env(&cmdline->dont_write_bytecode,
"PYTHONDONTWRITEBYTECODE");
pymain_set_flag_from_env(&cmdline->no_user_site_directory,
"PYTHONNOUSERSITE");
pymain_set_flag_from_env(&cmdline->use_unbuffered_io,
"PYTHONUNBUFFERED");
#ifdef MS_WINDOWS
pymain_set_flag_from_env(&cmdline->legacy_windows_fs_encoding,
"PYTHONLEGACYWINDOWSFSENCODING");
pymain_set_flag_from_env(&cmdline->legacy_windows_stdio,
"PYTHONLEGACYWINDOWSSTDIO");
#endif
}
static int
config_get_env_var_dup(wchar_t **dest, wchar_t *wname, char *name)
{
if (Py_IgnoreEnvironmentFlag) {
*dest = NULL;
return 0;
}
#ifdef MS_WINDOWS
const wchar_t *var = _wgetenv(wname);
if (!var || var[0] == '\0') {
*dest = NULL;
return 0;
}
wchar_t *copy = _PyMem_RawWcsdup(var);
if (copy == NULL) {
return -1;
}
*dest = copy;
#else
const char *var = getenv(name);
if (!var || var[0] == '\0') {
*dest = NULL;
return 0;
}
size_t len;
wchar_t *wvar = Py_DecodeLocale(var, &len);
if (!wvar) {
if (len == (size_t)-2) {
return -2;
}
else {
return -1;
}
}
*dest = wvar;
#endif
return 0;
}
static _PyInitError
config_init_pythonpath(_PyCoreConfig *config)
{
wchar_t *path;
int res = config_get_env_var_dup(&path, L"PYTHONPATH", "PYTHONPATH");
if (res < 0) {
return DECODE_LOCALE_ERR("PYTHONHOME", res);
}
config->module_search_path_env = path;
return _Py_INIT_OK();
}
static _PyInitError
config_init_home(_PyCoreConfig *config)
{
wchar_t *home;
/* If Py_SetPythonHome() was called, use its value */
home = _Py_path_config.home;
if (home) {
config->home = _PyMem_RawWcsdup(home);
if (config->home == NULL) {
return _Py_INIT_NO_MEMORY();
}
return _Py_INIT_OK();
}
int res = config_get_env_var_dup(&home, L"PYTHONHOME", "PYTHONHOME");
if (res < 0) {
return DECODE_LOCALE_ERR("PYTHONHOME", res);
}
config->home = home;
return _Py_INIT_OK();
}
static _PyInitError
config_init_hash_seed(_PyCoreConfig *config)
{
if (config->use_hash_seed < 0) {
const char *seed_text = pymain_get_env_var("PYTHONHASHSEED");
int use_hash_seed;
unsigned long hash_seed;
if (_Py_ReadHashSeed(seed_text, &use_hash_seed, &hash_seed) < 0) {
return _Py_INIT_USER_ERR("PYTHONHASHSEED must be \"random\" "
"or an integer in range [0; 4294967295]");
}
config->use_hash_seed = use_hash_seed;
config->hash_seed = hash_seed;
}
return _Py_INIT_OK();
}
_PyInitError
_PyCoreConfig_ReadEnv(_PyCoreConfig *config)
{
_PyInitError err = config_init_home(config);
if (_Py_INIT_FAILED(err)) {
return err;
}
err = config_init_pythonpath(config);
if (_Py_INIT_FAILED(err)) {
return err;
}
err = config_get_program_name(config);
if (_Py_INIT_FAILED(err)) {
return err;
}
err = config_init_hash_seed(config);
if (_Py_INIT_FAILED(err)) {
return err;
}
return _Py_INIT_OK();
}
static int
pymain_init_utf8_mode(_PyMain *pymain)
{
_PyCoreConfig *core_config = &pymain->core_config;
#ifdef MS_WINDOWS
if (pymain->cmdline.legacy_windows_fs_encoding) {
core_config->utf8_mode = 0;
return 0;
}
#endif
const wchar_t *xopt = pymain_get_xoption(pymain, L"utf8");
if (xopt) {
wchar_t *sep = wcschr(xopt, L'=');
if (sep) {
xopt = sep + 1;
if (wcscmp(xopt, L"1") == 0) {
core_config->utf8_mode = 1;
}
else if (wcscmp(xopt, L"0") == 0) {
core_config->utf8_mode = 0;
}
else {
pymain->err = _Py_INIT_USER_ERR("invalid -X utf8 option value");
return -1;
}
}
else {
core_config->utf8_mode = 1;
}
return 0;
}
const char *opt = pymain_get_env_var("PYTHONUTF8");
if (opt) {
if (strcmp(opt, "1") == 0) {
core_config->utf8_mode = 1;
}
else if (strcmp(opt, "0") == 0) {
core_config->utf8_mode = 0;
}
else {
pymain->err = _Py_INIT_USER_ERR("invalid PYTHONUTF8 environment "
"variable value");
return -1;
}
return 0;
}
return 0;
}
static int
pymain_parse_envvars(_PyMain *pymain)
{
_PyCoreConfig *core_config = &pymain->core_config;
/* Get environment variables */
pymain_set_flags_from_env(pymain);
if (pymain_warnings_envvar(pymain) < 0) {
return -1;
}
_PyInitError err = _PyCoreConfig_ReadEnv(&pymain->core_config);
if (_Py_INIT_FAILED(pymain->err)) {
pymain->err = err;
return -1;
}
if (pymain_get_program_name(pymain) < 0) {
return -1;
}
core_config->allocator = pymain_get_env_var("PYTHONMALLOC");
/* -X options */
if (pymain_get_xoption(pymain, L"showrefcount")) {
core_config->show_ref_count = 1;
}
if (pymain_get_xoption(pymain, L"showalloccount")) {
core_config->show_alloc_count = 1;
}
/* More complex options: env var and/or -X option */
if (pymain_get_env_var("PYTHONFAULTHANDLER")
|| pymain_get_xoption(pymain, L"faulthandler")) {
core_config->faulthandler = 1;
}
if (pymain_get_env_var("PYTHONPROFILEIMPORTTIME")
|| pymain_get_xoption(pymain, L"importtime")) {
core_config->import_time = 1;
}
if (pymain_init_tracemalloc(pymain) < 0) {
return -1;
}
if (pymain_get_xoption(pymain, L"dev" ) ||
pymain_get_env_var("PYTHONDEVMODE"))
{
core_config->dev_mode = 1;
core_config->faulthandler = 1;
core_config->allocator = "debug";
}
if (pymain_get_env_var("PYTHONDUMPREFS")) {
pymain->core_config.dump_refs = 1;
}
if (pymain_get_env_var("PYTHONMALLOCSTATS")) {
pymain->core_config.malloc_stats = 1;
}
const char* env = pymain_get_env_var("PYTHONCOERCECLOCALE");
if (env) {
if (strcmp(env, "0") == 0) {
pymain->core_config.coerce_c_locale = 0;
}
else if (strcmp(env, "warn") == 0) {
pymain->core_config.coerce_c_locale_warn = 1;
}
else {
pymain->core_config.coerce_c_locale = 1;
}
}
if (pymain_init_utf8_mode(pymain) < 0) {
return -1;
}
return 0;
}
/* Parse command line options and environment variables.
This code must not use Python runtime apart PyMem_Raw memory allocator.
Return 0 on success.
Return 1 if Python is done and must exit.
Set pymain->err and return -1 on error. */
static int
pymain_read_conf_impl(_PyMain *pymain)
{
int res = pymain_parse_cmdline(pymain);
if (res != 0) {
return res;
}
/* Set Py_IgnoreEnvironmentFlag for Py_GETENV() */
Py_IgnoreEnvironmentFlag = pymain->core_config.ignore_environment;
if (pymain_parse_envvars(pymain) < 0) {
return -1;
}
if (pymain_init_sys_argv(pymain) < 0) {
return -1;
}
_PyInitError err = _PyCoreConfig_Read(&pymain->core_config);
if (_Py_INIT_FAILED(err)) {
pymain->err = err;
return -1;
}
return 0;
}
static int
pymain_read_conf(_PyMain *pymain)
{
int res = -1;
/* Force default allocator, since pymain_free() must use the same allocator
than this function. */
PyMemAllocatorEx old_alloc;
_PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
char *oldloc = _PyMem_RawStrdup(setlocale(LC_ALL, NULL));
if (oldloc == NULL) {
pymain->err = _Py_INIT_NO_MEMORY();
goto done;
}
/* Reconfigure the locale to the default for this process */
_Py_SetLocaleFromEnv(LC_ALL);
int locale_coerced = 0;
int loops = 0;
int init_ignore_env = pymain->core_config.ignore_environment;
while (1) {
int utf8_mode = pymain->core_config.utf8_mode;
int encoding_changed = 0;
/* Watchdog to prevent an infinite loop */
loops++;
if (loops == 3) {
pymain->err = _Py_INIT_ERR("Encoding changed twice while "
"reading the configuration");
goto done;
}
if (pymain->use_bytes_argv) {
if (pymain_decode_bytes_argv(pymain) < 0) {
goto done;
}
}
res = pymain_read_conf_impl(pymain);
if (res != 0) {
goto done;
}
/* The legacy C locale assumes ASCII as the default text encoding, which
* causes problems not only for the CPython runtime, but also other
* components like GNU readline.
*
* Accordingly, when the CLI detects it, it attempts to coerce it to a
* more capable UTF-8 based alternative.
*
* See the documentation of the PYTHONCOERCECLOCALE setting for more
* details.
*/
if (pymain->core_config.coerce_c_locale == 1 && !locale_coerced) {
locale_coerced = 1;
_Py_CoerceLegacyLocale(&pymain->core_config);
encoding_changed = 1;
}
if (utf8_mode == -1) {
if (pymain->core_config.utf8_mode == 1) {
/* UTF-8 Mode enabled */
encoding_changed = 1;
}
}
else {
if (pymain->core_config.utf8_mode != utf8_mode) {
encoding_changed = 1;
}
}
if (!encoding_changed) {
break;
}
/* Reset the configuration, except UTF-8 Mode. Set Py_UTF8Mode for
Py_DecodeLocale(). Reset Py_IgnoreEnvironmentFlag, modified by
pymain_read_conf_impl(). */
Py_UTF8Mode = pymain->core_config.utf8_mode;
Py_IgnoreEnvironmentFlag = init_ignore_env;
pymain_clear_pymain(pymain);
pymain_get_global_config(pymain);
/* The encoding changed: read again the configuration
with the new encoding */
}
res = 0;
done:
if (oldloc != NULL) {
setlocale(LC_ALL, oldloc);
PyMem_RawFree(oldloc);
}
PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
return res;
}
/* Read configuration settings from standard locations
*
* This function doesn't make any changes to the interpreter state - it
* merely populates any missing configuration settings. This allows an
* embedding application to completely override a config option by
* setting it before calling this function, or else modify the default
* setting before passing the fully populated config to Py_EndInitialization.
*
* More advanced selective initialization tricks are possible by calling
* this function multiple times with various preconfigured settings.
*/
_PyInitError
_PyCoreConfig_Read(_PyCoreConfig *config)
{
if (config->program_name == NULL) {
#ifdef MS_WINDOWS
const wchar_t *program_name = L"python";
#else
const wchar_t *program_name = L"python3";
#endif
config->program_name = _PyMem_RawWcsdup(program_name);
if (config->program_name == NULL) {
return _Py_INIT_NO_MEMORY();
}
}
if (config->utf8_mode < 0 || config->coerce_c_locale < 0) {
if (_Py_LegacyLocaleDetected()) {
if (config->utf8_mode < 0) {
config->utf8_mode = 1;
}
if (config->coerce_c_locale < 0) {
config->coerce_c_locale = 1;
}
}
if (config->coerce_c_locale < 0) {
config->coerce_c_locale = 0;
}
if (config->utf8_mode < 0) {
config->utf8_mode = 0;
}
}
return _Py_INIT_OK();
}
void
_PyCoreConfig_Clear(_PyCoreConfig *config)
{
#define CLEAR(ATTR) \
do { \
PyMem_RawFree(ATTR); \
ATTR = NULL; \
} while (0)
CLEAR(config->module_search_path_env);
CLEAR(config->home);
CLEAR(config->program_name);
#undef CLEAR
}
int
_PyCoreConfig_Copy(_PyCoreConfig *config, const _PyCoreConfig *config2)
{
_PyCoreConfig_Clear(config);
#define COPY_ATTR(ATTR) config->ATTR = config2->ATTR
COPY_ATTR(ignore_environment);
COPY_ATTR(use_hash_seed);
COPY_ATTR(hash_seed);
COPY_ATTR(_disable_importlib);
COPY_ATTR(allocator);
COPY_ATTR(dev_mode);
COPY_ATTR(faulthandler);
COPY_ATTR(tracemalloc);
COPY_ATTR(import_time);
COPY_ATTR(show_ref_count);
COPY_ATTR(show_alloc_count);
COPY_ATTR(dump_refs);
COPY_ATTR(malloc_stats);
COPY_ATTR(utf8_mode);
#undef COPY_ATTR
#define COPY_STR_ATTR(ATTR) \
do { \
if (config2->ATTR != NULL) { \
config->ATTR = _PyMem_RawWcsdup(config2->ATTR); \
if (config->ATTR == NULL) { \
return -1; \
} \
} \
} while (0)
COPY_STR_ATTR(module_search_path_env);
COPY_STR_ATTR(home);
COPY_STR_ATTR(program_name);
#undef COPY_STR_ATTR
return 0;
}
void
_PyMainInterpreterConfig_Clear(_PyMainInterpreterConfig *config)
{
Py_CLEAR(config->argv);
Py_CLEAR(config->executable);
Py_CLEAR(config->prefix);
Py_CLEAR(config->base_prefix);
Py_CLEAR(config->exec_prefix);
Py_CLEAR(config->base_exec_prefix);
Py_CLEAR(config->warnoptions);
Py_CLEAR(config->xoptions);
Py_CLEAR(config->module_search_path);
}
static PyObject*
config_copy_attr(PyObject *obj)
{
if (PyUnicode_Check(obj)) {
Py_INCREF(obj);
return obj;
}
else if (PyList_Check(obj)) {
return PyList_GetSlice(obj, 0, Py_SIZE(obj));
}
else if (PyDict_Check(obj)) {
/* The dict type is used for xoptions. Make the assumption that keys
and values are immutables */
return PyDict_Copy(obj);
}
else {
PyErr_Format(PyExc_TypeError,
"cannot copy config attribute of type %.200s",
Py_TYPE(obj)->tp_name);
return NULL;
}
}
int
_PyMainInterpreterConfig_Copy(_PyMainInterpreterConfig *config,
const _PyMainInterpreterConfig *config2)
{
_PyMainInterpreterConfig_Clear(config);
#define COPY_ATTR(ATTR) \
do { \
if (config2->ATTR != NULL) { \
config->ATTR = config_copy_attr(config2->ATTR); \
if (config->ATTR == NULL) { \
return -1; \
} \
} \
} while (0)
COPY_ATTR(argv);
COPY_ATTR(executable);
COPY_ATTR(prefix);
COPY_ATTR(base_prefix);
COPY_ATTR(exec_prefix);
COPY_ATTR(base_exec_prefix);
COPY_ATTR(warnoptions);
COPY_ATTR(xoptions);
COPY_ATTR(module_search_path);
#undef COPY_ATTR
return 0;
}
static PyObject *
config_create_path_list(const wchar_t *path, wchar_t delim)
{
int i, n;
const wchar_t *p;
PyObject *v;
n = 1;
p = path;
while ((p = wcschr(p, delim)) != NULL) {
n++;
p++;
}
v = PyList_New(n);
if (v == NULL) {
return NULL;
}
for (i = 0; ; i++) {
p = wcschr(path, delim);
if (p == NULL) {
p = path + wcslen(path); /* End of string */
}
PyObject *w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
if (w == NULL) {
Py_DECREF(v);
return NULL;
}
PyList_SET_ITEM(v, i, w);
if (*p == '\0') {
break;
}
path = p+1;
}
return v;
}
_PyInitError
_PyMainInterpreterConfig_Read(_PyMainInterpreterConfig *config, _PyCoreConfig *core_config)
{
_PyInitError err = _PyPathConfig_Init(core_config);
if (_Py_INIT_FAILED(err)) {
return err;
}
/* Signal handlers are installed by default */
if (config->install_signal_handlers < 0) {
config->install_signal_handlers = 1;
}
if (config->module_search_path == NULL &&
!core_config->_disable_importlib)
{
wchar_t *sys_path = Py_GetPath();
config->module_search_path = config_create_path_list(sys_path, DELIM);
if (config->module_search_path == NULL) {
return _Py_INIT_NO_MEMORY();
}
}
if (config->executable == NULL) {
config->executable = PyUnicode_FromWideChar(Py_GetProgramFullPath(), -1);
if (config->executable == NULL) {
return _Py_INIT_NO_MEMORY();
}
}
if (config->prefix == NULL) {
config->prefix = PyUnicode_FromWideChar(Py_GetPrefix(), -1);
if (config->prefix == NULL) {
return _Py_INIT_NO_MEMORY();
}
}
if (config->exec_prefix == NULL) {
config->exec_prefix = PyUnicode_FromWideChar(Py_GetExecPrefix(), -1);
if (config->exec_prefix == NULL) {
return _Py_INIT_NO_MEMORY();
}
}
if (config->base_prefix == NULL) {
Py_INCREF(config->prefix);
config->base_prefix = config->prefix;
}
if (config->base_exec_prefix == NULL) {
Py_INCREF(config->exec_prefix);
config->base_exec_prefix = config->exec_prefix;
}
return _Py_INIT_OK();
}
static int
pymain_init_python_core(_PyMain *pymain)
{
pymain_set_global_config(pymain);
pymain_init_stdio(pymain);
pymain->err = _Py_InitializeCore(&pymain->core_config);
if (_Py_INIT_FAILED(pymain->err)) {
return -1;
}
return 0;
}
static int
pymain_init_python_main(_PyMain *pymain)
{
if (pymain_init_xoptions_dict(pymain)) {
pymain->err = _Py_INIT_NO_MEMORY();
return -1;
}
if (pymain_init_warnoptions(pymain)) {
pymain->err = _Py_INIT_NO_MEMORY();
return -1;
}
if (pymain_init_argv(pymain) < 0) {
pymain->err = _Py_INIT_ERR("failed to create sys.argv");
return -1;
}
_PyInitError err = _PyMainInterpreterConfig_Read(&pymain->config,
&pymain->core_config);
if (_Py_INIT_FAILED(err)) {
pymain->err = err;
return -1;
}
if (pymain_init_main_interpreter(pymain)) {
return -1;
}
if (pymain->cmdline.filename != NULL) {
/* If filename is a package (ex: directory or ZIP file) which contains
__main__.py, main_importer_path is set to filename and will be
prepended to sys.path by pymain_run_main_from_importer(). Otherwise,
main_importer_path is set to NULL. */
pymain->main_importer_path = pymain_get_importer(pymain->cmdline.filename);
}
if (pymain_update_sys_path(pymain) < 0) {
return -1;
}
return 0;
}
static void
pymain_run_python(_PyMain *pymain)
{
_Py_CommandLineDetails *cmdline = &pymain->cmdline;
pymain_header(pymain);
pymain_import_readline(pymain);
if (cmdline->command) {
pymain->status = pymain_run_command(cmdline->command, &pymain->cf);
}
else if (cmdline->module) {
pymain->status = (pymain_run_module(cmdline->module, 1) != 0);
}
else {
pymain_run_filename(pymain);
}
pymain_repl(pymain);
}
static int
pymain_init(_PyMain *pymain)
{
/* 754 requires that FP exceptions run in "no stop" mode by default,
* and until C vendors implement C99's ways to control FP exceptions,
* Python requires non-stop mode. Alas, some platforms enable FP
* exceptions by default. Here we disable them.
*/
#ifdef __FreeBSD__
fedisableexcept(FE_OVERFLOW);
#endif
pymain->err = _PyRuntime_Initialize();
if (_Py_INIT_FAILED(pymain->err)) {
return -1;
}
pymain->core_config._disable_importlib = 0;
pymain->config.install_signal_handlers = 1;
pymain_get_global_config(pymain);
return 0;
}
static int
pymain_impl(_PyMain *pymain)
{
if (pymain_init(pymain) < 0) {
return -1;
}
/* Read the configuration, but initialize also the LC_CTYPE locale:
enable UTF-8 mode (PEP 540) and/or coerce the C locale (PEP 538) */
int res = pymain_read_conf(pymain);
if (res < 0) {
return -1;
}
if (res > 0) {
/* --help or --version command: we are done */
return 0;
}
_Py_CommandLineDetails *cmdline = &pymain->cmdline;
if (cmdline->print_help) {
pymain_usage(0, pymain->argv[0]);
return 0;
}
if (cmdline->print_version) {
printf("Python %s\n",
(cmdline->print_version >= 2) ? Py_GetVersion() : PY_VERSION);
return 0;
}
orig_argc = pymain->argc; /* For Py_GetArgcArgv() */
orig_argv = pymain->argv;
res = pymain_init_python_core(pymain);
if (res < 0) {
return -1;
}
res = pymain_init_python_main(pymain);
if (res < 0) {
return -1;
}
pymain_run_python(pymain);
pymain_clear_python(pymain);
if (Py_FinalizeEx() < 0) {
/* Value unlikely to be confused with a non-error exit status or
other special meaning */
pymain->status = 120;
}
return 0;
}
static int
pymain_main(_PyMain *pymain)
{
memset(&pymain->cmdline, 0, sizeof(pymain->cmdline));
if (pymain_impl(pymain) < 0) {
_Py_FatalInitError(pymain->err);
}
pymain_free(pymain);
orig_argc = 0;
orig_argv = NULL;
return pymain->status;
}
int
Py_Main(int argc, wchar_t **argv)
{
_PyMain pymain = _PyMain_INIT;
pymain.argc = argc;
pymain.argv = argv;
return pymain_main(&pymain);
}
int
_Py_UnixMain(int argc, char **argv)
{
_PyMain pymain = _PyMain_INIT;
pymain.argc = argc;
pymain.use_bytes_argv = 1;
pymain.bytes_argv = argv;
return pymain_main(&pymain);
}
/* this is gonna seem *real weird*, but if you put some other code between
Py_Main() and Py_GetArgcArgv() you will need to adjust the test in the
while statement in Misc/gdbinit:ppystack */
/* Make the *original* argc/argv available to other modules.
This is rare, but it is needed by the secureware extension. */
void
Py_GetArgcArgv(int *argc, wchar_t ***argv)
{
*argc = orig_argc;
*argv = orig_argv;
}
#ifdef __cplusplus
}
#endif
|