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
|
/* System module */
/*
Various bits of information used by the interpreter are collected in
module 'sys'.
Function member:
- exit(sts): raise SystemExit
Data members:
- stdin, stdout, stderr: standard file objects
- modules: the table of modules (dictionary)
- path: module search path (list of strings)
- argv: script arguments (list of strings)
- ps1, ps2: optional primary and secondary prompts (strings)
*/
#include "Python.h"
#include "structseq.h"
#include "code.h"
#include "frameobject.h"
#include "eval.h"
#include "osdefs.h"
#ifdef MS_WINDOWS
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif /* MS_WINDOWS */
#ifdef MS_COREDLL
extern void *PyWin_DLLhModule;
/* A string loaded from the DLL at startup: */
extern const char *PyWin_DLLVersionString;
#endif
#ifdef __VMS
#include <unixlib.h>
#endif
#ifdef HAVE_LANGINFO_H
#include <locale.h>
#include <langinfo.h>
#endif
PyObject *
PySys_GetObject(const char *name)
{
PyThreadState *tstate = PyThreadState_GET();
PyObject *sd = tstate->interp->sysdict;
if (sd == NULL)
return NULL;
return PyDict_GetItemString(sd, name);
}
int
PySys_SetObject(const char *name, PyObject *v)
{
PyThreadState *tstate = PyThreadState_GET();
PyObject *sd = tstate->interp->sysdict;
if (v == NULL) {
if (PyDict_GetItemString(sd, name) == NULL)
return 0;
else
return PyDict_DelItemString(sd, name);
}
else
return PyDict_SetItemString(sd, name, v);
}
static PyObject *
sys_displayhook(PyObject *self, PyObject *o)
{
PyObject *outf;
PyInterpreterState *interp = PyThreadState_GET()->interp;
PyObject *modules = interp->modules;
PyObject *builtins = PyDict_GetItemString(modules, "builtins");
if (builtins == NULL) {
PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
return NULL;
}
/* Print value except if None */
/* After printing, also assign to '_' */
/* Before, set '_' to None to avoid recursion */
if (o == Py_None) {
Py_INCREF(Py_None);
return Py_None;
}
if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)
return NULL;
outf = PySys_GetObject("stdout");
if (outf == NULL || outf == Py_None) {
PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
return NULL;
}
if (PyFile_WriteObject(o, outf, 0) != 0)
return NULL;
if (PyFile_WriteString("\n", outf) != 0)
return NULL;
if (PyObject_SetAttrString(builtins, "_", o) != 0)
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(displayhook_doc,
"displayhook(object) -> None\n"
"\n"
"Print an object to sys.stdout and also save it in builtins.\n"
);
static PyObject *
sys_excepthook(PyObject* self, PyObject* args)
{
PyObject *exc, *value, *tb;
if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
return NULL;
PyErr_Display(exc, value, tb);
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(excepthook_doc,
"excepthook(exctype, value, traceback) -> None\n"
"\n"
"Handle an exception by displaying it with a traceback on sys.stderr.\n"
);
static PyObject *
sys_exc_info(PyObject *self, PyObject *noargs)
{
PyThreadState *tstate;
tstate = PyThreadState_GET();
return Py_BuildValue(
"(OOO)",
tstate->exc_type != NULL ? tstate->exc_type : Py_None,
tstate->exc_value != NULL ? tstate->exc_value : Py_None,
tstate->exc_traceback != NULL ?
tstate->exc_traceback : Py_None);
}
PyDoc_STRVAR(exc_info_doc,
"exc_info() -> (type, value, traceback)\n\
\n\
Return information about the most recent exception caught by an except\n\
clause in the current stack frame or in an older stack frame."
);
static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
PyObject *exit_code = 0;
if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
return NULL;
/* Raise SystemExit so callers may catch it or clean up. */
PyErr_SetObject(PyExc_SystemExit, exit_code);
return NULL;
}
PyDoc_STRVAR(exit_doc,
"exit([status])\n\
\n\
Exit the interpreter by raising SystemExit(status).\n\
If the status is omitted or None, it defaults to zero (i.e., success).\n\
If the status is numeric, it will be used as the system exit status.\n\
If it is another kind of object, it will be printed and the system\n\
exit status will be one (i.e., failure)."
);
static PyObject *
sys_getdefaultencoding(PyObject *self)
{
return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
}
PyDoc_STRVAR(getdefaultencoding_doc,
"getdefaultencoding() -> string\n\
\n\
Return the current default string encoding used by the Unicode \n\
implementation."
);
static PyObject *
sys_setdefaultencoding(PyObject *self, PyObject *args)
{
char *encoding;
if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding))
return NULL;
if (PyUnicode_SetDefaultEncoding(encoding))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(setdefaultencoding_doc,
"setdefaultencoding(encoding)\n\
\n\
Set the current default string encoding used by the Unicode implementation."
);
static PyObject *
sys_getfilesystemencoding(PyObject *self)
{
if (Py_FileSystemDefaultEncoding)
return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(getfilesystemencoding_doc,
"getfilesystemencoding() -> string\n\
\n\
Return the encoding used to convert Unicode filenames in\n\
operating system filenames."
);
static PyObject *
sys_setfilesystemencoding(PyObject *self, PyObject *args)
{
PyObject *new_encoding;
if (!PyArg_ParseTuple(args, "U:setfilesystemencoding", &new_encoding))
return NULL;
if (_Py_SetFileSystemEncoding(new_encoding))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(setfilesystemencoding_doc,
"setfilesystemencoding(string) -> None\n\
\n\
Set the encoding used to convert Unicode filenames in\n\
operating system filenames."
);
static PyObject *
sys_intern(PyObject *self, PyObject *args)
{
PyObject *s;
if (!PyArg_ParseTuple(args, "U:intern", &s))
return NULL;
if (PyUnicode_CheckExact(s)) {
Py_INCREF(s);
PyUnicode_InternInPlace(&s);
return s;
}
else {
PyErr_Format(PyExc_TypeError,
"can't intern %.400s", s->ob_type->tp_name);
return NULL;
}
}
PyDoc_STRVAR(intern_doc,
"intern(string) -> string\n\
\n\
``Intern'' the given string. This enters the string in the (global)\n\
table of interned strings whose purpose is to speed up dictionary lookups.\n\
Return the string itself or the previously interned string object with the\n\
same value.");
/*
* Cached interned string objects used for calling the profile and
* trace functions. Initialized by trace_init().
*/
static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
static int
trace_init(void)
{
static char *whatnames[7] = {"call", "exception", "line", "return",
"c_call", "c_exception", "c_return"};
PyObject *name;
int i;
for (i = 0; i < 7; ++i) {
if (whatstrings[i] == NULL) {
name = PyUnicode_InternFromString(whatnames[i]);
if (name == NULL)
return -1;
whatstrings[i] = name;
}
}
return 0;
}
static PyObject *
call_trampoline(PyThreadState *tstate, PyObject* callback,
PyFrameObject *frame, int what, PyObject *arg)
{
PyObject *args = PyTuple_New(3);
PyObject *whatstr;
PyObject *result;
if (args == NULL)
return NULL;
Py_INCREF(frame);
whatstr = whatstrings[what];
Py_INCREF(whatstr);
if (arg == NULL)
arg = Py_None;
Py_INCREF(arg);
PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
PyTuple_SET_ITEM(args, 1, whatstr);
PyTuple_SET_ITEM(args, 2, arg);
/* call the Python-level function */
PyFrame_FastToLocals(frame);
result = PyEval_CallObject(callback, args);
PyFrame_LocalsToFast(frame, 1);
if (result == NULL)
PyTraceBack_Here(frame);
/* cleanup */
Py_DECREF(args);
return result;
}
static int
profile_trampoline(PyObject *self, PyFrameObject *frame,
int what, PyObject *arg)
{
PyThreadState *tstate = frame->f_tstate;
PyObject *result;
if (arg == NULL)
arg = Py_None;
result = call_trampoline(tstate, self, frame, what, arg);
if (result == NULL) {
PyEval_SetProfile(NULL, NULL);
return -1;
}
Py_DECREF(result);
return 0;
}
static int
trace_trampoline(PyObject *self, PyFrameObject *frame,
int what, PyObject *arg)
{
PyThreadState *tstate = frame->f_tstate;
PyObject *callback;
PyObject *result;
if (what == PyTrace_CALL)
callback = self;
else
callback = frame->f_trace;
if (callback == NULL)
return 0;
result = call_trampoline(tstate, callback, frame, what, arg);
if (result == NULL) {
PyEval_SetTrace(NULL, NULL);
Py_XDECREF(frame->f_trace);
frame->f_trace = NULL;
return -1;
}
if (result != Py_None) {
PyObject *temp = frame->f_trace;
frame->f_trace = NULL;
Py_XDECREF(temp);
frame->f_trace = result;
}
else {
Py_DECREF(result);
}
return 0;
}
static PyObject *
sys_settrace(PyObject *self, PyObject *args)
{
if (trace_init() == -1)
return NULL;
if (args == Py_None)
PyEval_SetTrace(NULL, NULL);
else
PyEval_SetTrace(trace_trampoline, args);
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(settrace_doc,
"settrace(function)\n\
\n\
Set the global debug tracing function. It will be called on each\n\
function call. See the debugger chapter in the library manual."
);
static PyObject *
sys_gettrace(PyObject *self, PyObject *args)
{
PyThreadState *tstate = PyThreadState_GET();
PyObject *temp = tstate->c_traceobj;
if (temp == NULL)
temp = Py_None;
Py_INCREF(temp);
return temp;
}
PyDoc_STRVAR(gettrace_doc,
"gettrace()\n\
\n\
Return the global debug tracing function set with sys.settrace.\n\
See the debugger chapter in the library manual."
);
static PyObject *
sys_setprofile(PyObject *self, PyObject *args)
{
if (trace_init() == -1)
return NULL;
if (args == Py_None)
PyEval_SetProfile(NULL, NULL);
else
PyEval_SetProfile(profile_trampoline, args);
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(setprofile_doc,
"setprofile(function)\n\
\n\
Set the profiling function. It will be called on each function call\n\
and return. See the profiler chapter in the library manual."
);
static PyObject *
sys_getprofile(PyObject *self, PyObject *args)
{
PyThreadState *tstate = PyThreadState_GET();
PyObject *temp = tstate->c_profileobj;
if (temp == NULL)
temp = Py_None;
Py_INCREF(temp);
return temp;
}
PyDoc_STRVAR(getprofile_doc,
"getprofile()\n\
\n\
Return the profiling function set with sys.setprofile.\n\
See the profiler chapter in the library manual."
);
static PyObject *
sys_setcheckinterval(PyObject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_Py_CheckInterval))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(setcheckinterval_doc,
"setcheckinterval(n)\n\
\n\
Tell the Python interpreter to check for asynchronous events every\n\
n instructions. This also affects how often thread switches occur."
);
static PyObject *
sys_getcheckinterval(PyObject *self, PyObject *args)
{
return PyLong_FromLong(_Py_CheckInterval);
}
PyDoc_STRVAR(getcheckinterval_doc,
"getcheckinterval() -> current check interval; see setcheckinterval()."
);
#ifdef WITH_TSC
static PyObject *
sys_settscdump(PyObject *self, PyObject *args)
{
int bool;
PyThreadState *tstate = PyThreadState_Get();
if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
return NULL;
if (bool)
tstate->interp->tscdump = 1;
else
tstate->interp->tscdump = 0;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(settscdump_doc,
"settscdump(bool)\n\
\n\
If true, tell the Python interpreter to dump VM measurements to\n\
stderr. If false, turn off dump. The measurements are based on the\n\
processor's time-stamp counter."
);
#endif /* TSC */
static PyObject *
sys_setrecursionlimit(PyObject *self, PyObject *args)
{
int new_limit;
if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
return NULL;
if (new_limit <= 0) {
PyErr_SetString(PyExc_ValueError,
"recursion limit must be positive");
return NULL;
}
Py_SetRecursionLimit(new_limit);
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(setrecursionlimit_doc,
"setrecursionlimit(n)\n\
\n\
Set the maximum depth of the Python interpreter stack to n. This\n\
limit prevents infinite recursion from causing an overflow of the C\n\
stack and crashing Python. The highest possible limit is platform-\n\
dependent."
);
static PyObject *
sys_getrecursionlimit(PyObject *self)
{
return PyLong_FromLong(Py_GetRecursionLimit());
}
PyDoc_STRVAR(getrecursionlimit_doc,
"getrecursionlimit()\n\
\n\
Return the current value of the recursion limit, the maximum depth\n\
of the Python interpreter stack. This limit prevents infinite\n\
recursion from causing an overflow of the C stack and crashing Python."
);
#ifdef MS_WINDOWS
PyDoc_STRVAR(getwindowsversion_doc,
"getwindowsversion()\n\
\n\
Return information about the running version of Windows.\n\
The result is a tuple of (major, minor, build, platform, text)\n\
All elements are numbers, except text which is a string.\n\
Platform may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP\n\
"
);
static PyObject *
sys_getwindowsversion(PyObject *self)
{
OSVERSIONINFO ver;
ver.dwOSVersionInfoSize = sizeof(ver);
if (!GetVersionEx(&ver))
return PyErr_SetFromWindowsErr(0);
return Py_BuildValue("HHHHs",
ver.dwMajorVersion,
ver.dwMinorVersion,
ver.dwBuildNumber,
ver.dwPlatformId,
ver.szCSDVersion);
}
#endif /* MS_WINDOWS */
#ifdef HAVE_DLOPEN
static PyObject *
sys_setdlopenflags(PyObject *self, PyObject *args)
{
int new_val;
PyThreadState *tstate = PyThreadState_GET();
if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
return NULL;
if (!tstate)
return NULL;
tstate->interp->dlopenflags = new_val;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(setdlopenflags_doc,
"setdlopenflags(n) -> None\n\
\n\
Set the flags that will be used for dlopen() calls. Among other\n\
things, this will enable a lazy resolving of symbols when importing\n\
a module, if called as sys.setdlopenflags(0)\n\
To share symbols across extension modules, call as\n\
sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)"
);
static PyObject *
sys_getdlopenflags(PyObject *self, PyObject *args)
{
PyThreadState *tstate = PyThreadState_GET();
if (!tstate)
return NULL;
return PyLong_FromLong(tstate->interp->dlopenflags);
}
PyDoc_STRVAR(getdlopenflags_doc,
"getdlopenflags() -> int\n\
\n\
Return the current value of the flags that are used for dlopen()\n\
calls. The flag constants are defined in the dl module."
);
#endif
#ifdef USE_MALLOPT
/* Link with -lmalloc (or -lmpc) on an SGI */
#include <malloc.h>
static PyObject *
sys_mdebug(PyObject *self, PyObject *args)
{
int flag;
if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
return NULL;
mallopt(M_DEBUG, flag);
Py_INCREF(Py_None);
return Py_None;
}
#endif /* USE_MALLOPT */
static PyObject *
sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
{
PyObject *res = NULL;
static PyObject *str__sizeof__, *gc_head_size = NULL;
static char *kwlist[] = {"object", "default", 0};
PyObject *o, *dflt = NULL;
PyObject *method;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
kwlist, &o, &dflt))
return NULL;
/* Initialize static variable needed by _PyType_Lookup */
if (str__sizeof__ == NULL) {
str__sizeof__ = PyUnicode_InternFromString("__sizeof__");
if (str__sizeof__ == NULL)
return NULL;
}
/* Initialize static variable for GC head size */
if (gc_head_size == NULL) {
gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head));
if (gc_head_size == NULL)
return NULL;
}
/* Make sure the type is initialized. float gets initialized late */
if (PyType_Ready(Py_TYPE(o)) < 0)
return NULL;
method = _PyType_Lookup(Py_TYPE(o), str__sizeof__);
if (method == NULL)
PyErr_Format(PyExc_TypeError,
"Type %.100s doesn't define __sizeof__",
Py_TYPE(o)->tp_name);
else
res = PyObject_CallFunctionObjArgs(method, o, NULL);
/* Has a default value been given */
if ((res == NULL) && (dflt != NULL) &&
PyErr_ExceptionMatches(PyExc_TypeError))
{
PyErr_Clear();
Py_INCREF(dflt);
return dflt;
}
else if (res == NULL)
return res;
/* add gc_head size */
if (PyObject_IS_GC(o)) {
PyObject *tmp = res;
res = PyNumber_Add(tmp, gc_head_size);
Py_DECREF(tmp);
}
return res;
}
PyDoc_STRVAR(getsizeof_doc,
"getsizeof(object, default) -> int\n\
\n\
Return the size of object in bytes.");
static PyObject *
sys_getrefcount(PyObject *self, PyObject *arg)
{
return PyLong_FromSsize_t(arg->ob_refcnt);
}
#ifdef Py_REF_DEBUG
static PyObject *
sys_gettotalrefcount(PyObject *self)
{
return PyLong_FromSsize_t(_Py_GetRefTotal());
}
#endif /* Py_REF_DEBUG */
PyDoc_STRVAR(getrefcount_doc,
"getrefcount(object) -> integer\n\
\n\
Return the reference count of object. The count returned is generally\n\
one higher than you might expect, because it includes the (temporary)\n\
reference as an argument to getrefcount()."
);
#ifdef COUNT_ALLOCS
static PyObject *
sys_getcounts(PyObject *self)
{
extern PyObject *get_counts(void);
return get_counts();
}
#endif
PyDoc_STRVAR(getframe_doc,
"_getframe([depth]) -> frameobject\n\
\n\
Return a frame object from the call stack. If optional integer depth is\n\
given, return the frame object that many calls below the top of the stack.\n\
If that is deeper than the call stack, ValueError is raised. The default\n\
for depth is zero, returning the frame at the top of the call stack.\n\
\n\
This function should be used for internal and specialized\n\
purposes only."
);
static PyObject *
sys_getframe(PyObject *self, PyObject *args)
{
PyFrameObject *f = PyThreadState_GET()->frame;
int depth = -1;
if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
return NULL;
while (depth > 0 && f != NULL) {
f = f->f_back;
--depth;
}
if (f == NULL) {
PyErr_SetString(PyExc_ValueError,
"call stack is not deep enough");
return NULL;
}
Py_INCREF(f);
return (PyObject*)f;
}
PyDoc_STRVAR(current_frames_doc,
"_current_frames() -> dictionary\n\
\n\
Return a dictionary mapping each current thread T's thread id to T's\n\
current stack frame.\n\
\n\
This function should be used for specialized purposes only."
);
static PyObject *
sys_current_frames(PyObject *self, PyObject *noargs)
{
return _PyThread_CurrentFrames();
}
PyDoc_STRVAR(call_tracing_doc,
"call_tracing(func, args) -> object\n\
\n\
Call func(*args), while tracing is enabled. The tracing state is\n\
saved, and restored afterwards. This is intended to be called from\n\
a debugger from a checkpoint, to recursively debug some other code."
);
static PyObject *
sys_call_tracing(PyObject *self, PyObject *args)
{
PyObject *func, *funcargs;
if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
return NULL;
return _PyEval_CallTracing(func, funcargs);
}
PyDoc_STRVAR(callstats_doc,
"callstats() -> tuple of integers\n\
\n\
Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
when Python was built. Otherwise, return None.\n\
\n\
When enabled, this function returns detailed, implementation-specific\n\
details about the number of function calls executed. The return value is\n\
a 11-tuple where the entries in the tuple are counts of:\n\
0. all function calls\n\
1. calls to PyFunction_Type objects\n\
2. PyFunction calls that do not create an argument tuple\n\
3. PyFunction calls that do not create an argument tuple\n\
and bypass PyEval_EvalCodeEx()\n\
4. PyMethod calls\n\
5. PyMethod calls on bound methods\n\
6. PyType calls\n\
7. PyCFunction calls\n\
8. generator calls\n\
9. All other calls\n\
10. Number of stack pops performed by call_function()"
);
#ifdef __cplusplus
extern "C" {
#endif
#ifdef Py_TRACE_REFS
/* Defined in objects.c because it uses static globals if that file */
extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
#endif
#ifdef DYNAMIC_EXECUTION_PROFILE
/* Defined in ceval.c because it uses static globals if that file */
extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
#endif
#ifdef __cplusplus
}
#endif
static PyObject *
sys_clear_type_cache(PyObject* self, PyObject* args)
{
PyType_ClearCache();
Py_RETURN_NONE;
}
PyDoc_STRVAR(sys_clear_type_cache__doc__,
"_clear_type_cache() -> None\n\
Clear the internal type lookup cache.");
static PyMethodDef sys_methods[] = {
/* Might as well keep this in alphabetic order */
{"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
callstats_doc},
{"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
sys_clear_type_cache__doc__},
{"_current_frames", sys_current_frames, METH_NOARGS,
current_frames_doc},
{"displayhook", sys_displayhook, METH_O, displayhook_doc},
{"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
{"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
{"exit", sys_exit, METH_VARARGS, exit_doc},
{"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
METH_NOARGS, getdefaultencoding_doc},
#ifdef HAVE_DLOPEN
{"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
getdlopenflags_doc},
#endif
#ifdef COUNT_ALLOCS
{"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
#endif
#ifdef DYNAMIC_EXECUTION_PROFILE
{"getdxp", _Py_GetDXProfile, METH_VARARGS},
#endif
{"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
METH_NOARGS, getfilesystemencoding_doc},
#ifdef Py_TRACE_REFS
{"getobjects", _Py_GetObjects, METH_VARARGS},
#endif
#ifdef Py_REF_DEBUG
{"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
#endif
{"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
{"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
getrecursionlimit_doc},
{"getsizeof", (PyCFunction)sys_getsizeof,
METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
{"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
#ifdef MS_WINDOWS
{"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
getwindowsversion_doc},
#endif /* MS_WINDOWS */
{"intern", sys_intern, METH_VARARGS, intern_doc},
#ifdef USE_MALLOPT
{"mdebug", sys_mdebug, METH_VARARGS},
#endif
{"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS,
setdefaultencoding_doc},
{"setfilesystemencoding", sys_setfilesystemencoding, METH_VARARGS,
setfilesystemencoding_doc},
{"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
setcheckinterval_doc},
{"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
getcheckinterval_doc},
#ifdef HAVE_DLOPEN
{"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
setdlopenflags_doc},
#endif
{"setprofile", sys_setprofile, METH_O, setprofile_doc},
{"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
{"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
setrecursionlimit_doc},
#ifdef WITH_TSC
{"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
#endif
{"settrace", sys_settrace, METH_O, settrace_doc},
{"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
{"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
{NULL, NULL} /* sentinel */
};
static PyObject *
list_builtin_module_names(void)
{
PyObject *list = PyList_New(0);
int i;
if (list == NULL)
return NULL;
for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
PyObject *name = PyUnicode_FromString(
PyImport_Inittab[i].name);
if (name == NULL)
break;
PyList_Append(list, name);
Py_DECREF(name);
}
if (PyList_Sort(list) != 0) {
Py_DECREF(list);
list = NULL;
}
if (list) {
PyObject *v = PyList_AsTuple(list);
Py_DECREF(list);
list = v;
}
return list;
}
static PyObject *warnoptions = NULL;
void
PySys_ResetWarnOptions(void)
{
if (warnoptions == NULL || !PyList_Check(warnoptions))
return;
PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
}
void
PySys_AddWarnOption(const wchar_t *s)
{
PyObject *str;
if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Py_XDECREF(warnoptions);
warnoptions = PyList_New(0);
if (warnoptions == NULL)
return;
}
str = PyUnicode_FromWideChar(s, -1);
if (str != NULL) {
PyList_Append(warnoptions, str);
Py_DECREF(str);
}
}
int
PySys_HasWarnOptions(void)
{
return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
}
/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
Two literals concatenated works just fine. If you have a K&R compiler
or other abomination that however *does* understand longer strings,
get rid of the !!! comment in the middle and the quotes that surround it. */
PyDoc_VAR(sys_doc) =
PyDoc_STR(
"This module provides access to some objects used or maintained by the\n\
interpreter and to functions that interact strongly with the interpreter.\n\
\n\
Dynamic objects:\n\
\n\
argv -- command line arguments; argv[0] is the script pathname if known\n\
path -- module search path; path[0] is the script directory, else ''\n\
modules -- dictionary of loaded modules\n\
\n\
displayhook -- called to show results in an interactive session\n\
excepthook -- called to handle any uncaught exception other than SystemExit\n\
To customize printing in an interactive session or to install a custom\n\
top-level exception handler, assign other functions to replace these.\n\
\n\
stdin -- standard input file object; used by input()\n\
stdout -- standard output file object; used by print()\n\
stderr -- standard error object; used for error messages\n\
By assigning other file objects (or objects that behave like files)\n\
to these, it is possible to redirect all of the interpreter's I/O.\n\
\n\
last_type -- type of last uncaught exception\n\
last_value -- value of last uncaught exception\n\
last_traceback -- traceback of last uncaught exception\n\
These three are only available in an interactive session after a\n\
traceback has been printed.\n\
"
)
/* concatenating string here */
PyDoc_STR(
"\n\
Static objects:\n\
\n\
float_info -- a dict with information about the float implementation.\n\
maxsize -- the largest supported length of containers.\n\
maxunicode -- the largest supported character\n\
builtin_module_names -- tuple of module names built into this interpreter\n\
subversion -- subversion information of the build as tuple\n\
version -- the version of this interpreter as a string\n\
version_info -- version information as a tuple\n\
hexversion -- version information encoded as a single integer\n\
copyright -- copyright notice pertaining to this interpreter\n\
platform -- platform identifier\n\
executable -- pathname of this Python interpreter\n\
prefix -- prefix used to find the Python library\n\
exec_prefix -- prefix used to find the machine-specific Python library\n\
"
)
#ifdef MS_WINDOWS
/* concatenating string here */
PyDoc_STR(
"dllhandle -- [Windows only] integer handle of the Python DLL\n\
winver -- [Windows only] version number of the Python DLL\n\
"
)
#endif /* MS_WINDOWS */
PyDoc_STR(
"__stdin__ -- the original stdin; don't touch!\n\
__stdout__ -- the original stdout; don't touch!\n\
__stderr__ -- the original stderr; don't touch!\n\
__displayhook__ -- the original displayhook; don't touch!\n\
__excepthook__ -- the original excepthook; don't touch!\n\
\n\
Functions:\n\
\n\
displayhook() -- print an object to the screen, and save it in builtins._\n\
excepthook() -- print an exception and its traceback to sys.stderr\n\
exc_info() -- return thread-safe information about the current exception\n\
exit() -- exit the interpreter by raising SystemExit\n\
getdlopenflags() -- returns flags to be used for dlopen() calls\n\
getprofile() -- get the global profiling function\n\
getrefcount() -- return the reference count for an object (plus one :-)\n\
getrecursionlimit() -- return the max recursion depth for the interpreter\n\
getsizeof() -- return the size of an object in bytes\n\
gettrace() -- get the global debug tracing function\n\
setcheckinterval() -- control how often the interpreter checks for events\n\
setdlopenflags() -- set the flags to be used for dlopen() calls\n\
setprofile() -- set the global profiling function\n\
setrecursionlimit() -- set the max recursion depth for the interpreter\n\
settrace() -- set the global debug tracing function\n\
"
)
/* end of sys_doc */ ;
/* Subversion branch and revision management */
static const char _patchlevel_revision[] = PY_PATCHLEVEL_REVISION;
static const char headurl[] = "$HeadURL$";
static int svn_initialized;
static char patchlevel_revision[50]; /* Just the number */
static char branch[50];
static char shortbranch[50];
static const char *svn_revision;
static void
svnversion_init(void)
{
const char *python, *br_start, *br_end, *br_end2, *svnversion;
Py_ssize_t len;
int istag = 0;
if (svn_initialized)
return;
python = strstr(headurl, "/python/");
if (!python) {
strcpy(branch, "unknown branch");
strcpy(shortbranch, "unknown");
}
else {
br_start = python + 8;
br_end = strchr(br_start, '/');
assert(br_end);
/* Works even for trunk,
as we are in trunk/Python/sysmodule.c */
br_end2 = strchr(br_end+1, '/');
istag = strncmp(br_start, "tags", 4) == 0;
if (strncmp(br_start, "trunk", 5) == 0) {
strcpy(branch, "trunk");
strcpy(shortbranch, "trunk");
}
else if (istag || strncmp(br_start, "branches", 8) == 0) {
len = br_end2 - br_start;
strncpy(branch, br_start, len);
branch[len] = '\0';
len = br_end2 - (br_end + 1);
strncpy(shortbranch, br_end + 1, len);
shortbranch[len] = '\0';
}
else {
Py_FatalError("bad HeadURL");
return;
}
}
svnversion = _Py_svnversion();
if (strcmp(svnversion, "exported") != 0)
svn_revision = svnversion;
else if (istag) {
len = strlen(_patchlevel_revision);
assert(len >= 13);
assert(len < (sizeof(patchlevel_revision) + 13));
strncpy(patchlevel_revision, _patchlevel_revision + 11,
len - 13);
patchlevel_revision[len - 13] = '\0';
svn_revision = patchlevel_revision;
}
else
svn_revision = "";
svn_initialized = 1;
}
/* Return svnversion output if available.
Else return Revision of patchlevel.h if on branch.
Else return empty string */
const char*
Py_SubversionRevision()
{
svnversion_init();
return svn_revision;
}
const char*
Py_SubversionShortBranch()
{
svnversion_init();
return shortbranch;
}
PyDoc_STRVAR(flags__doc__,
"sys.flags\n\
\n\
Flags provided through command line arguments or environment vars.");
static PyTypeObject FlagsType;
static PyStructSequence_Field flags_fields[] = {
{"debug", "-d"},
{"division_warning", "-Q"},
{"inspect", "-i"},
{"interactive", "-i"},
{"optimize", "-O or -OO"},
{"dont_write_bytecode", "-B"},
{"no_user_site", "-s"},
{"no_site", "-S"},
{"ignore_environment", "-E"},
{"verbose", "-v"},
#ifdef RISCOS
{"riscos_wimp", "???"},
#endif
/* {"unbuffered", "-u"}, */
/* {"skip_first", "-x"}, */
{"bytes_warning", "-b"},
{0}
};
static PyStructSequence_Desc flags_desc = {
"sys.flags", /* name */
flags__doc__, /* doc */
flags_fields, /* fields */
#ifdef RISCOS
12
#else
11
#endif
};
static PyObject*
make_flags(void)
{
int pos = 0;
PyObject *seq;
seq = PyStructSequence_New(&FlagsType);
if (seq == NULL)
return NULL;
#define SetFlag(flag) \
PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
SetFlag(Py_DebugFlag);
SetFlag(Py_DivisionWarningFlag);
SetFlag(Py_InspectFlag);
SetFlag(Py_InteractiveFlag);
SetFlag(Py_OptimizeFlag);
SetFlag(Py_DontWriteBytecodeFlag);
SetFlag(Py_NoUserSiteDirectory);
SetFlag(Py_NoSiteFlag);
SetFlag(Py_IgnoreEnvironmentFlag);
SetFlag(Py_VerboseFlag);
#ifdef RISCOS
SetFlag(Py_RISCOSWimpFlag);
#endif
/* SetFlag(saw_unbuffered_flag); */
/* SetFlag(skipfirstline); */
SetFlag(Py_BytesWarningFlag);
#undef SetFlag
if (PyErr_Occurred()) {
return NULL;
}
return seq;
}
static struct PyModuleDef sysmodule = {
PyModuleDef_HEAD_INIT,
"sys",
sys_doc,
-1, /* multiple "initialization" just copies the module dict. */
sys_methods,
NULL,
NULL,
NULL,
NULL
};
invalid character on encoding error.
Use the Py_DecodeLocale() function to decode the bytes string back to a wide
character string. */
char*
Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
{
return encode_locale(text, error_pos, 0, 0);
}
/* Similar to Py_EncodeLocale(), but result must be freed by PyMem_RawFree()
instead of PyMem_Free(). */
char*
_Py_EncodeLocaleRaw(const wchar_t *text, size_t *error_pos)
{
return encode_locale(text, error_pos, 1, 0);
}
int
_Py_EncodeLocaleEx(const wchar_t *text, char **str,
size_t *error_pos, const char **reason,
int current_locale, _Py_error_handler errors)
{
return encode_locale_ex(text, str, error_pos, reason, 1,
current_locale, errors);
}
// Get the current locale encoding name:
//
// - Return "utf-8" if _Py_FORCE_UTF8_LOCALE macro is defined (ex: on Android)
// - Return "utf-8" if the UTF-8 Mode is enabled
// - On Windows, return the ANSI code page (ex: "cp1250")
// - Return "utf-8" if nl_langinfo(CODESET) returns an empty string.
// - Otherwise, return nl_langinfo(CODESET).
//
// Return NULL on memory allocation failure.
//
// See also config_get_locale_encoding()
wchar_t*
_Py_GetLocaleEncoding(void)
{
#ifdef _Py_FORCE_UTF8_LOCALE
// On Android langinfo.h and CODESET are missing,
// and UTF-8 is always used in mbstowcs() and wcstombs().
return _PyMem_RawWcsdup(L"utf-8");
#else
#ifdef MS_WINDOWS
wchar_t encoding[23];
unsigned int ansi_codepage = GetACP();
swprintf(encoding, Py_ARRAY_LENGTH(encoding), L"cp%u", ansi_codepage);
encoding[Py_ARRAY_LENGTH(encoding) - 1] = 0;
return _PyMem_RawWcsdup(encoding);
#else
const char *encoding = nl_langinfo(CODESET);
if (!encoding || encoding[0] == '\0') {
// Use UTF-8 if nl_langinfo() returns an empty string. It can happen on
// macOS if the LC_CTYPE locale is not supported.
return _PyMem_RawWcsdup(L"utf-8");
}
wchar_t *wstr;
int res = decode_current_locale(encoding, &wstr, NULL,
NULL, _Py_ERROR_SURROGATEESCAPE);
if (res < 0) {
return NULL;
}
return wstr;
#endif // !MS_WINDOWS
#endif // !_Py_FORCE_UTF8_LOCALE
}
PyObject *
_Py_GetLocaleEncodingObject(void)
{
wchar_t *encoding = _Py_GetLocaleEncoding();
if (encoding == NULL) {
PyErr_NoMemory();
return NULL;
}
PyObject *str = PyUnicode_FromWideChar(encoding, -1);
PyMem_RawFree(encoding);
return str;
}
#ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
/* Check whether current locale uses Unicode as internal wchar_t form. */
int
_Py_LocaleUsesNonUnicodeWchar(void)
{
/* Oracle Solaris uses non-Unicode internal wchar_t form for
non-Unicode locales and hence needs conversion to UTF first. */
char* codeset = nl_langinfo(CODESET);
if (!codeset) {
return 0;
}
/* 646 refers to ISO/IEC 646 standard that corresponds to ASCII encoding */
return (strcmp(codeset, "UTF-8") != 0 && strcmp(codeset, "646") != 0);
}
static wchar_t *
_Py_ConvertWCharForm(const wchar_t *source, Py_ssize_t size,
const char *tocode, const char *fromcode)
{
static_assert(sizeof(wchar_t) == 4, "wchar_t must be 32-bit");
/* Ensure we won't overflow the size. */
if (size > (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t))) {
PyErr_NoMemory();
return NULL;
}
/* the string doesn't have to be NULL terminated */
wchar_t* target = PyMem_Malloc(size * sizeof(wchar_t));
if (target == NULL) {
PyErr_NoMemory();
return NULL;
}
iconv_t cd = iconv_open(tocode, fromcode);
if (cd == (iconv_t)-1) {
PyErr_Format(PyExc_ValueError, "iconv_open() failed");
PyMem_Free(target);
return NULL;
}
char *inbuf = (char *) source;
char *outbuf = (char *) target;
size_t inbytesleft = sizeof(wchar_t) * size;
size_t outbytesleft = inbytesleft;
size_t ret = iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
if (ret == DECODE_ERROR) {
PyErr_Format(PyExc_ValueError, "iconv() failed");
PyMem_Free(target);
iconv_close(cd);
return NULL;
}
iconv_close(cd);
return target;
}
/* Convert a wide character string to the UCS-4 encoded string. This
is necessary on systems where internal form of wchar_t are not Unicode
code points (e.g. Oracle Solaris).
Return a pointer to a newly allocated string, use PyMem_Free() to free
the memory. Return NULL and raise exception on conversion or memory
allocation error. */
wchar_t *
_Py_DecodeNonUnicodeWchar(const wchar_t *native, Py_ssize_t size)
{
return _Py_ConvertWCharForm(native, size, "UCS-4-INTERNAL", "wchar_t");
}
/* Convert a UCS-4 encoded string to native wide character string. This
is necessary on systems where internal form of wchar_t are not Unicode
code points (e.g. Oracle Solaris).
The conversion is done in place. This can be done because both wchar_t
and UCS-4 use 4-byte encoding, and one wchar_t symbol always correspond
to a single UCS-4 symbol and vice versa. (This is true for Oracle Solaris,
which is currently the only system using these functions; it doesn't have
to be for other systems).
Return 0 on success. Return -1 and raise exception on conversion
or memory allocation error. */
int
_Py_EncodeNonUnicodeWchar_InPlace(wchar_t *unicode, Py_ssize_t size)
{
wchar_t* result = _Py_ConvertWCharForm(unicode, size, "wchar_t", "UCS-4-INTERNAL");
if (!result) {
return -1;
}
memcpy(unicode, result, size * sizeof(wchar_t));
PyMem_Free(result);
return 0;
}
#endif /* HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION */
#ifdef MS_WINDOWS
static __int64 secs_between_epochs = 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */
static void
FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, time_t *time_out, int* nsec_out)
{
/* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
/* Cannot simply cast and dereference in_ptr,
since it might not be aligned properly */
__int64 in;
memcpy(&in, in_ptr, sizeof(in));
*nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */
*time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, time_t);
}
void
_Py_time_t_to_FILE_TIME(time_t time_in, int nsec_in, FILETIME *out_ptr)
{
/* XXX endianness */
__int64 out;
out = time_in + secs_between_epochs;
out = out * 10000000 + nsec_in / 100;
memcpy(out_ptr, &out, sizeof(out));
}
/* Below, we *know* that ugo+r is 0444 */
#if _S_IREAD != 0400
#error Unsupported C library
#endif
static int
attributes_to_mode(DWORD attr)
{
int m = 0;
if (attr & FILE_ATTRIBUTE_DIRECTORY)
m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */
else
m |= _S_IFREG;
if (attr & FILE_ATTRIBUTE_READONLY)
m |= 0444;
else
m |= 0666;
return m;
}
void
_Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *info, ULONG reparse_tag,
struct _Py_stat_struct *result)
{
memset(result, 0, sizeof(*result));
result->st_mode = attributes_to_mode(info->dwFileAttributes);
result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow;
result->st_dev = info->dwVolumeSerialNumber;
result->st_rdev = result->st_dev;
FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
result->st_nlink = info->nNumberOfLinks;
result->st_ino = (((uint64_t)info->nFileIndexHigh) << 32) + info->nFileIndexLow;
/* bpo-37834: Only actual symlinks set the S_IFLNK flag. But lstat() will
open other name surrogate reparse points without traversing them. To
detect/handle these, check st_file_attributes and st_reparse_tag. */
result->st_reparse_tag = reparse_tag;
if (info->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT &&
reparse_tag == IO_REPARSE_TAG_SYMLINK) {
/* first clear the S_IFMT bits */
result->st_mode ^= (result->st_mode & S_IFMT);
/* now set the bits that make this a symlink */
result->st_mode |= S_IFLNK;
}
result->st_file_attributes = info->dwFileAttributes;
}
#endif
/* Return information about a file.
On POSIX, use fstat().
On Windows, use GetFileType() and GetFileInformationByHandle() which support
files larger than 2 GiB. fstat() may fail with EOVERFLOW on files larger
than 2 GiB because the file size type is a signed 32-bit integer: see issue
#23152.
On Windows, set the last Windows error and return nonzero on error. On
POSIX, set errno and return nonzero on error. Fill status and return 0 on
success. */
int
_Py_fstat_noraise(int fd, struct _Py_stat_struct *status)
{
#ifdef MS_WINDOWS
BY_HANDLE_FILE_INFORMATION info;
HANDLE h;
int type;
h = _Py_get_osfhandle_noraise(fd);
if (h == INVALID_HANDLE_VALUE) {
/* errno is already set by _get_osfhandle, but we also set
the Win32 error for callers who expect that */
SetLastError(ERROR_INVALID_HANDLE);
return -1;
}
memset(status, 0, sizeof(*status));
type = GetFileType(h);
if (type == FILE_TYPE_UNKNOWN) {
DWORD error = GetLastError();
if (error != 0) {
errno = winerror_to_errno(error);
return -1;
}
/* else: valid but unknown file */
}
if (type != FILE_TYPE_DISK) {
if (type == FILE_TYPE_CHAR)
status->st_mode = _S_IFCHR;
else if (type == FILE_TYPE_PIPE)
status->st_mode = _S_IFIFO;
return 0;
}
if (!GetFileInformationByHandle(h, &info)) {
/* The Win32 error is already set, but we also set errno for
callers who expect it */
errno = winerror_to_errno(GetLastError());
return -1;
}
_Py_attribute_data_to_stat(&info, 0, status);
return 0;
#else
return fstat(fd, status);
#endif
}
/* Return information about a file.
On POSIX, use fstat().
On Windows, use GetFileType() and GetFileInformationByHandle() which support
files larger than 2 GiB. fstat() may fail with EOVERFLOW on files larger
than 2 GiB because the file size type is a signed 32-bit integer: see issue
#23152.
Raise an exception and return -1 on error. On Windows, set the last Windows
error on error. On POSIX, set errno on error. Fill status and return 0 on
success.
Release the GIL to call GetFileType() and GetFileInformationByHandle(), or
to call fstat(). The caller must hold the GIL. */
int
_Py_fstat(int fd, struct _Py_stat_struct *status)
{
int res;
assert(PyGILState_Check());
Py_BEGIN_ALLOW_THREADS
res = _Py_fstat_noraise(fd, status);
Py_END_ALLOW_THREADS
if (res != 0) {
#ifdef MS_WINDOWS
PyErr_SetFromWindowsErr(0);
#else
PyErr_SetFromErrno(PyExc_OSError);
#endif
return -1;
}
return 0;
}
/* Like _Py_stat() but with a raw filename. */
int
_Py_wstat(const wchar_t* path, struct stat *buf)
{
int err;
#ifdef MS_WINDOWS
struct _stat wstatbuf;
err = _wstat(path, &wstatbuf);
if (!err) {
buf->st_mode = wstatbuf.st_mode;
}
#else
char *fname;
fname = _Py_EncodeLocaleRaw(path, NULL);
if (fname == NULL) {
errno = EINVAL;
return -1;
}
err = stat(fname, buf);
PyMem_RawFree(fname);
#endif
return err;
}
/* Call _wstat() on Windows, or encode the path to the filesystem encoding and
call stat() otherwise. Only fill st_mode attribute on Windows.
Return 0 on success, -1 on _wstat() / stat() error, -2 if an exception was
raised. */
int
_Py_stat(PyObject *path, struct stat *statbuf)
{
#ifdef MS_WINDOWS
int err;
wchar_t *wpath = PyUnicode_AsWideCharString(path, NULL);
if (wpath == NULL)
return -2;
err = _Py_wstat(wpath, statbuf);
PyMem_Free(wpath);
return err;
#else
int ret;
PyObject *bytes;
char *cpath;
bytes = PyUnicode_EncodeFSDefault(path);
if (bytes == NULL)
return -2;
/* check for embedded null bytes */
if (PyBytes_AsStringAndSize(bytes, &cpath, NULL) == -1) {
Py_DECREF(bytes);
return -2;
}
ret = stat(cpath, statbuf);
Py_DECREF(bytes);
return ret;
#endif
}
#ifdef MS_WINDOWS
// For some Windows API partitions, SetHandleInformation() is declared
// but none of the handle flags are defined.
#ifndef HANDLE_FLAG_INHERIT
#define HANDLE_FLAG_INHERIT 0x00000001
#endif
#endif
/* This function MUST be kept async-signal-safe on POSIX when raise=0. */
static int
get_inheritable(int fd, int raise)
{
#ifdef MS_WINDOWS
HANDLE handle;
DWORD flags;
handle = _Py_get_osfhandle_noraise(fd);
if (handle == INVALID_HANDLE_VALUE) {
if (raise)
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
if (!GetHandleInformation(handle, &flags)) {
if (raise)
PyErr_SetFromWindowsErr(0);
return -1;
}
return (flags & HANDLE_FLAG_INHERIT);
#else
int flags;
flags = fcntl(fd, F_GETFD, 0);
if (flags == -1) {
if (raise)
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
return !(flags & FD_CLOEXEC);
#endif
}
/* Get the inheritable flag of the specified file descriptor.
Return 1 if the file descriptor can be inherited, 0 if it cannot,
raise an exception and return -1 on error. */
int
_Py_get_inheritable(int fd)
{
return get_inheritable(fd, 1);
}
/* This function MUST be kept async-signal-safe on POSIX when raise=0. */
static int
set_inheritable(int fd, int inheritable, int raise, int *atomic_flag_works)
{
#ifdef MS_WINDOWS
HANDLE handle;
DWORD flags;
#else
#if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
static int ioctl_works = -1;
int request;
int err;
#endif
int flags, new_flags;
int res;
#endif
/* atomic_flag_works can only be used to make the file descriptor
non-inheritable */
assert(!(atomic_flag_works != NULL && inheritable));
if (atomic_flag_works != NULL && !inheritable) {
if (*atomic_flag_works == -1) {
int isInheritable = get_inheritable(fd, raise);
if (isInheritable == -1)
return -1;
*atomic_flag_works = !isInheritable;
}
if (*atomic_flag_works)
return 0;
}
#ifdef MS_WINDOWS
handle = _Py_get_osfhandle_noraise(fd);
if (handle == INVALID_HANDLE_VALUE) {
if (raise)
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
if (inheritable)
flags = HANDLE_FLAG_INHERIT;
else
flags = 0;
if (!SetHandleInformation(handle, HANDLE_FLAG_INHERIT, flags)) {
if (raise)
PyErr_SetFromWindowsErr(0);
return -1;
}
return 0;
#else
#if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
if (ioctl_works != 0 && raise != 0) {
/* fast-path: ioctl() only requires one syscall */
/* caveat: raise=0 is an indicator that we must be async-signal-safe
* thus avoid using ioctl() so we skip the fast-path. */
if (inheritable)
request = FIONCLEX;
else
request = FIOCLEX;
err = ioctl(fd, request, NULL);
if (!err) {
ioctl_works = 1;
return 0;
}
#ifdef O_PATH
if (errno == EBADF) {
// bpo-44849: On Linux and FreeBSD, ioctl(FIOCLEX) fails with EBADF
// on O_PATH file descriptors. Fall through to the fcntl()
// implementation.
}
else
#endif
if (errno != ENOTTY && errno != EACCES) {
if (raise)
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
else {
/* Issue #22258: Here, ENOTTY means "Inappropriate ioctl for
device". The ioctl is declared but not supported by the kernel.
Remember that ioctl() doesn't work. It is the case on
Illumos-based OS for example.
Issue #27057: When SELinux policy disallows ioctl it will fail
with EACCES. While FIOCLEX is safe operation it may be
unavailable because ioctl was denied altogether.
This can be the case on Android. */
ioctl_works = 0;
}
/* fallback to fcntl() if ioctl() does not work */
}
#endif
/* slow-path: fcntl() requires two syscalls */
flags = fcntl(fd, F_GETFD);
if (flags < 0) {
if (raise)
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
if (inheritable) {
new_flags = flags & ~FD_CLOEXEC;
}
else {
new_flags = flags | FD_CLOEXEC;
}
if (new_flags == flags) {
/* FD_CLOEXEC flag already set/cleared: nothing to do */
return 0;
}
res = fcntl(fd, F_SETFD, new_flags);
if (res < 0) {
if (raise)
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
return 0;
#endif
}
/* Make the file descriptor non-inheritable.
Return 0 on success, set errno and return -1 on error. */
static int
make_non_inheritable(int fd)
{
return set_inheritable(fd, 0, 0, NULL);
}
/* Set the inheritable flag of the specified file descriptor.
On success: return 0, on error: raise an exception and return -1.
If atomic_flag_works is not NULL:
* if *atomic_flag_works==-1, check if the inheritable is set on the file
descriptor: if yes, set *atomic_flag_works to 1, otherwise set to 0 and
set the inheritable flag
* if *atomic_flag_works==1: do nothing
* if *atomic_flag_works==0: set inheritable flag to False
Set atomic_flag_works to NULL if no atomic flag was used to create the
file descriptor.
atomic_flag_works can only be used to make a file descriptor
non-inheritable: atomic_flag_works must be NULL if inheritable=1. */
int
_Py_set_inheritable(int fd, int inheritable, int *atomic_flag_works)
{
return set_inheritable(fd, inheritable, 1, atomic_flag_works);
}
/* Same as _Py_set_inheritable() but on error, set errno and
don't raise an exception.
This function is async-signal-safe. */
int
_Py_set_inheritable_async_safe(int fd, int inheritable, int *atomic_flag_works)
{
return set_inheritable(fd, inheritable, 0, atomic_flag_works);
}
static int
_Py_open_impl(const char *pathname, int flags, int gil_held)
{
int fd;
int async_err = 0;
#ifndef MS_WINDOWS
int *atomic_flag_works;
#endif
#ifdef MS_WINDOWS
flags |= O_NOINHERIT;
#elif defined(O_CLOEXEC)
atomic_flag_works = &_Py_open_cloexec_works;
flags |= O_CLOEXEC;
#else
atomic_flag_works = NULL;
#endif
if (gil_held) {
PyObject *pathname_obj = PyUnicode_DecodeFSDefault(pathname);
if (pathname_obj == NULL) {
return -1;
}
if (PySys_Audit("open", "OOi", pathname_obj, Py_None, flags) < 0) {
Py_DECREF(pathname_obj);
return -1;
}
do {
Py_BEGIN_ALLOW_THREADS
fd = open(pathname, flags);
Py_END_ALLOW_THREADS
} while (fd < 0
&& errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (async_err) {
Py_DECREF(pathname_obj);
return -1;
}
if (fd < 0) {
PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, pathname_obj, NULL);
Py_DECREF(pathname_obj);
return -1;
}
Py_DECREF(pathname_obj);
}
else {
fd = open(pathname, flags);
if (fd < 0)
return -1;
}
#ifndef MS_WINDOWS
if (set_inheritable(fd, 0, gil_held, atomic_flag_works) < 0) {
close(fd);
return -1;
}
#endif
return fd;
}
/* Open a file with the specified flags (wrapper to open() function).
Return a file descriptor on success. Raise an exception and return -1 on
error.
The file descriptor is created non-inheritable.
When interrupted by a signal (open() fails with EINTR), retry the syscall,
except if the Python signal handler raises an exception.
Release the GIL to call open(). The caller must hold the GIL. */
int
_Py_open(const char *pathname, int flags)
{
/* _Py_open() must be called with the GIL held. */
assert(PyGILState_Check());
return _Py_open_impl(pathname, flags, 1);
}
/* Open a file with the specified flags (wrapper to open() function).
Return a file descriptor on success. Set errno and return -1 on error.
The file descriptor is created non-inheritable.
If interrupted by a signal, fail with EINTR. */
int
_Py_open_noraise(const char *pathname, int flags)
{
return _Py_open_impl(pathname, flags, 0);
}
/* Open a file. Use _wfopen() on Windows, encode the path to the locale
encoding and use fopen() otherwise.
The file descriptor is created non-inheritable.
If interrupted by a signal, fail with EINTR. */
FILE *
_Py_wfopen(const wchar_t *path, const wchar_t *mode)
{
FILE *f;
if (PySys_Audit("open", "uui", path, mode, 0) < 0) {
return NULL;
}
#ifndef MS_WINDOWS
char *cpath;
char cmode[10];
size_t r;
r = wcstombs(cmode, mode, 10);
if (r == DECODE_ERROR || r >= 10) {
errno = EINVAL;
return NULL;
}
cpath = _Py_EncodeLocaleRaw(path, NULL);
if (cpath == NULL) {
return NULL;
}
f = fopen(cpath, cmode);
PyMem_RawFree(cpath);
#else
f = _wfopen(path, mode);
#endif
if (f == NULL)
return NULL;
if (make_non_inheritable(fileno(f)) < 0) {
fclose(f);
return NULL;
}
return f;
}
/* Open a file. Call _wfopen() on Windows, or encode the path to the filesystem
encoding and call fopen() otherwise.
Return the new file object on success. Raise an exception and return NULL
on error.
The file descriptor is created non-inheritable.
When interrupted by a signal (open() fails with EINTR), retry the syscall,
except if the Python signal handler raises an exception.
Release the GIL to call _wfopen() or fopen(). The caller must hold
the GIL. */
FILE*
_Py_fopen_obj(PyObject *path, const char *mode)
{
FILE *f;
int async_err = 0;
#ifdef MS_WINDOWS
wchar_t wmode[10];
int usize;
assert(PyGILState_Check());
if (PySys_Audit("open", "Osi", path, mode, 0) < 0) {
return NULL;
}
if (!PyUnicode_Check(path)) {
PyErr_Format(PyExc_TypeError,
"str file path expected under Windows, got %R",
Py_TYPE(path));
return NULL;
}
wchar_t *wpath = PyUnicode_AsWideCharString(path, NULL);
if (wpath == NULL)
return NULL;
usize = MultiByteToWideChar(CP_ACP, 0, mode, -1,
wmode, Py_ARRAY_LENGTH(wmode));
if (usize == 0) {
PyErr_SetFromWindowsErr(0);
PyMem_Free(wpath);
return NULL;
}
do {
Py_BEGIN_ALLOW_THREADS
f = _wfopen(wpath, wmode);
Py_END_ALLOW_THREADS
} while (f == NULL
&& errno == EINTR && !(async_err = PyErr_CheckSignals()));
PyMem_Free(wpath);
#else
PyObject *bytes;
const char *path_bytes;
assert(PyGILState_Check());
if (!PyUnicode_FSConverter(path, &bytes))
return NULL;
path_bytes = PyBytes_AS_STRING(bytes);
if (PySys_Audit("open", "Osi", path, mode, 0) < 0) {
Py_DECREF(bytes);
return NULL;
}
do {
Py_BEGIN_ALLOW_THREADS
f = fopen(path_bytes, mode);
Py_END_ALLOW_THREADS
} while (f == NULL
&& errno == EINTR && !(async_err = PyErr_CheckSignals()));
Py_DECREF(bytes);
#endif
if (async_err)
return NULL;
if (f == NULL) {
PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
return NULL;
}
if (set_inheritable(fileno(f), 0, 1, NULL) < 0) {
fclose(f);
return NULL;
}
return f;
}
/* Read count bytes from fd into buf.
On success, return the number of read bytes, it can be lower than count.
If the current file offset is at or past the end of file, no bytes are read,
and read() returns zero.
On error, raise an exception, set errno and return -1.
When interrupted by a signal (read() fails with EINTR), retry the syscall.
If the Python signal handler raises an exception, the function returns -1
(the syscall is not retried).
Release the GIL to call read(). The caller must hold the GIL. */
Py_ssize_t
_Py_read(int fd, void *buf, size_t count)
{
Py_ssize_t n;
int err;
int async_err = 0;
assert(PyGILState_Check());
/* _Py_read() must not be called with an exception set, otherwise the
* caller may think that read() was interrupted by a signal and the signal
* handler raised an exception. */
assert(!PyErr_Occurred());
if (count > _PY_READ_MAX) {
count = _PY_READ_MAX;
}
_Py_BEGIN_SUPPRESS_IPH
do {
Py_BEGIN_ALLOW_THREADS
errno = 0;
#ifdef MS_WINDOWS
_doserrno = 0;
n = read(fd, buf, (int)count);
// read() on a non-blocking empty pipe fails with EINVAL, which is
// mapped from the Windows error code ERROR_NO_DATA.
if (n < 0 && errno == EINVAL) {
if (_doserrno == ERROR_NO_DATA) {
errno = EAGAIN;
}
}
#else
n = read(fd, buf, count);
#endif
/* save/restore errno because PyErr_CheckSignals()
* and PyErr_SetFromErrno() can modify it */
err = errno;
Py_END_ALLOW_THREADS
} while (n < 0 && err == EINTR &&
!(async_err = PyErr_CheckSignals()));
_Py_END_SUPPRESS_IPH
if (async_err) {
/* read() was interrupted by a signal (failed with EINTR)
* and the Python signal handler raised an exception */
errno = err;
assert(errno == EINTR && PyErr_Occurred());
return -1;
}
if (n < 0) {
PyErr_SetFromErrno(PyExc_OSError);
errno = err;
return -1;
}
return n;
}
static Py_ssize_t
_Py_write_impl(int fd, const void *buf, size_t count, int gil_held)
{
Py_ssize_t n;
int err;
int async_err = 0;
_Py_BEGIN_SUPPRESS_IPH
#ifdef MS_WINDOWS
if (count > 32767) {
/* Issue #11395: the Windows console returns an error (12: not
enough space error) on writing into stdout if stdout mode is
binary and the length is greater than 66,000 bytes (or less,
depending on heap usage). */
if (gil_held) {
Py_BEGIN_ALLOW_THREADS
if (isatty(fd)) {
count = 32767;
}
Py_END_ALLOW_THREADS
} else {
if (isatty(fd)) {
count = 32767;
}
}
}
#endif
if (count > _PY_WRITE_MAX) {
count = _PY_WRITE_MAX;
}
if (gil_held) {
do {
Py_BEGIN_ALLOW_THREADS
errno = 0;
#ifdef MS_WINDOWS
// write() on a non-blocking pipe fails with ENOSPC on Windows if
// the pipe lacks available space for the entire buffer.
int c = (int)count;
do {
_doserrno = 0;
n = write(fd, buf, c);
if (n >= 0 || errno != ENOSPC || _doserrno != 0) {
break;
}
errno = EAGAIN;
c /= 2;
} while (c > 0);
#else
n = write(fd, buf, count);
#endif
/* save/restore errno because PyErr_CheckSignals()
* and PyErr_SetFromErrno() can modify it */
err = errno;
Py_END_ALLOW_THREADS
} while (n < 0 && err == EINTR &&
!(async_err = PyErr_CheckSignals()));
}
else {
do {
errno = 0;
#ifdef MS_WINDOWS
// write() on a non-blocking pipe fails with ENOSPC on Windows if
// the pipe lacks available space for the entire buffer.
int c = (int)count;
do {
_doserrno = 0;
n = write(fd, buf, c);
if (n >= 0 || errno != ENOSPC || _doserrno != 0) {
break;
}
errno = EAGAIN;
c /= 2;
} while (c > 0);
#else
n = write(fd, buf, count);
#endif
err = errno;
} while (n < 0 && err == EINTR);
}
_Py_END_SUPPRESS_IPH
if (async_err) {
/* write() was interrupted by a signal (failed with EINTR)
and the Python signal handler raised an exception (if gil_held is
nonzero). */
errno = err;
assert(errno == EINTR && (!gil_held || PyErr_Occurred()));
return -1;
}
if (n < 0) {
if (gil_held)
PyErr_SetFromErrno(PyExc_OSError);
errno = err;
return -1;
}
return n;
}
/* Write count bytes of buf into fd.
On success, return the number of written bytes, it can be lower than count
including 0. On error, raise an exception, set errno and return -1.
When interrupted by a signal (write() fails with EINTR), retry the syscall.
If the Python signal handler raises an exception, the function returns -1
(the syscall is not retried).
Release the GIL to call write(). The caller must hold the GIL. */
Py_ssize_t
_Py_write(int fd, const void *buf, size_t count)
{
assert(PyGILState_Check());
/* _Py_write() must not be called with an exception set, otherwise the
* caller may think that write() was interrupted by a signal and the signal
* handler raised an exception. */
assert(!PyErr_Occurred());
return _Py_write_impl(fd, buf, count, 1);
}
/* Write count bytes of buf into fd.
*
* On success, return the number of written bytes, it can be lower than count
* including 0. On error, set errno and return -1.
*
* When interrupted by a signal (write() fails with EINTR), retry the syscall
* without calling the Python signal handler. */
Py_ssize_t
_Py_write_noraise(int fd, const void *buf, size_t count)
{
return _Py_write_impl(fd, buf, count, 0);
}
#ifdef HAVE_READLINK
/* Read value of symbolic link. Encode the path to the locale encoding, decode
the result from the locale encoding.
Return -1 on encoding error, on readlink() error, if the internal buffer is
too short, on decoding error, or if 'buf' is too short. */
int
_Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t buflen)
{
char *cpath;
char cbuf[MAXPATHLEN];
size_t cbuf_len = Py_ARRAY_LENGTH(cbuf);
wchar_t *wbuf;
Py_ssize_t res;
size_t r1;
cpath = _Py_EncodeLocaleRaw(path, NULL);
if (cpath == NULL) {
errno = EINVAL;
return -1;
}
res = readlink(cpath, cbuf, cbuf_len);
PyMem_RawFree(cpath);
if (res == -1) {
return -1;
}
if ((size_t)res == cbuf_len) {
errno = EINVAL;
return -1;
}
cbuf[res] = '\0'; /* buf will be null terminated */
wbuf = Py_DecodeLocale(cbuf, &r1);
if (wbuf == NULL) {
errno = EINVAL;
return -1;
}
/* wbuf must have space to store the trailing NUL character */
if (buflen <= r1) {
PyMem_RawFree(wbuf);
errno = EINVAL;
return -1;
}
wcsncpy(buf, wbuf, buflen);
PyMem_RawFree(wbuf);
return (int)r1;
}
#endif
#ifdef HAVE_REALPATH
/* Return the canonicalized absolute pathname. Encode path to the locale
encoding, decode the result from the locale encoding.
Return NULL on encoding error, realpath() error, decoding error
or if 'resolved_path' is too short. */
wchar_t*
_Py_wrealpath(const wchar_t *path,
wchar_t *resolved_path, size_t resolved_path_len)
{
char *cpath;
char cresolved_path[MAXPATHLEN];
wchar_t *wresolved_path;
char *res;
size_t r;
cpath = _Py_EncodeLocaleRaw(path, NULL);
if (cpath == NULL) {
errno = EINVAL;
return NULL;
}
res = realpath(cpath, cresolved_path);
PyMem_RawFree(cpath);
if (res == NULL)
return NULL;
wresolved_path = Py_DecodeLocale(cresolved_path, &r);
if (wresolved_path == NULL) {
errno = EINVAL;
return NULL;
}
/* wresolved_path must have space to store the trailing NUL character */
if (resolved_path_len <= r) {
PyMem_RawFree(wresolved_path);
errno = EINVAL;
return NULL;
}
wcsncpy(resolved_path, wresolved_path, resolved_path_len);
PyMem_RawFree(wresolved_path);
return resolved_path;
}
#endif
int
_Py_isabs(const wchar_t *path)
{
#ifdef MS_WINDOWS
const wchar_t *tail;
HRESULT hr = PathCchSkipRoot(path, &tail);
if (FAILED(hr) || path == tail) {
return 0;
}
if (tail == &path[1] && (path[0] == SEP || path[0] == ALTSEP)) {
// Exclude paths with leading SEP
return 0;
}
if (tail == &path[2] && path[1] == L':') {
// Exclude drive-relative paths (e.g. C:filename.ext)
return 0;
}
return 1;
#else
return (path[0] == SEP);
#endif
}
/* Get an absolute path.
On error (ex: fail to get the current directory), return -1.
On memory allocation failure, set *abspath_p to NULL and return 0.
On success, return a newly allocated to *abspath_p to and return 0.
The string must be freed by PyMem_RawFree(). */
int
_Py_abspath(const wchar_t *path, wchar_t **abspath_p)
{
if (path[0] == '\0' || !wcscmp(path, L".")) {
wchar_t cwd[MAXPATHLEN + 1];
cwd[Py_ARRAY_LENGTH(cwd) - 1] = 0;
if (!_Py_wgetcwd(cwd, Py_ARRAY_LENGTH(cwd) - 1)) {
/* unable to get the current directory */
return -1;
}
*abspath_p = _PyMem_RawWcsdup(cwd);
return 0;
}
if (_Py_isabs(path)) {
*abspath_p = _PyMem_RawWcsdup(path);
return 0;
}
#ifdef MS_WINDOWS
return _PyOS_getfullpathname(path, abspath_p);
#else
wchar_t cwd[MAXPATHLEN + 1];
cwd[Py_ARRAY_LENGTH(cwd) - 1] = 0;
if (!_Py_wgetcwd(cwd, Py_ARRAY_LENGTH(cwd) - 1)) {
/* unable to get the current directory */
return -1;
}
size_t cwd_len = wcslen(cwd);
size_t path_len = wcslen(path);
size_t len = cwd_len + 1 + path_len + 1;
if (len <= (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t)) {
*abspath_p = PyMem_RawMalloc(len * sizeof(wchar_t));
}
else {
*abspath_p = NULL;
}
if (*abspath_p == NULL) {
return 0;
}
wchar_t *abspath = *abspath_p;
memcpy(abspath, cwd, cwd_len * sizeof(wchar_t));
abspath += cwd_len;
*abspath = (wchar_t)SEP;
abspath++;
memcpy(abspath, path, path_len * sizeof(wchar_t));
abspath += path_len;
*abspath = 0;
return 0;
#endif
}
// The Windows Games API family implements the PathCch* APIs in the Xbox OS,
// but does not expose them yet. Load them dynamically until
// 1) they are officially exposed
// 2) we stop supporting older versions of the GDK which do not expose them
#if defined(MS_WINDOWS_GAMES) && !defined(MS_WINDOWS_DESKTOP)
HRESULT
PathCchSkipRoot(const wchar_t *path, const wchar_t **rootEnd)
{
static int initialized = 0;
typedef HRESULT(__stdcall *PPathCchSkipRoot) (PCWSTR pszPath,
PCWSTR *ppszRootEnd);
static PPathCchSkipRoot _PathCchSkipRoot;
if (initialized == 0) {
HMODULE pathapi = LoadLibraryExW(L"api-ms-win-core-path-l1-1-0.dll", NULL,
LOAD_LIBRARY_SEARCH_SYSTEM32);
if (pathapi) {
_PathCchSkipRoot = (PPathCchSkipRoot)GetProcAddress(
pathapi, "PathCchSkipRoot");
}
else {
_PathCchSkipRoot = NULL;
}
initialized = 1;
}
if (!_PathCchSkipRoot) {
return E_NOINTERFACE;
}
return _PathCchSkipRoot(path, rootEnd);
}
static HRESULT
PathCchCombineEx(wchar_t *buffer, size_t bufsize, const wchar_t *dirname,
const wchar_t *relfile, unsigned long flags)
{
static int initialized = 0;
typedef HRESULT(__stdcall *PPathCchCombineEx) (PWSTR pszPathOut,
size_t cchPathOut,
PCWSTR pszPathIn,
PCWSTR pszMore,
unsigned long dwFlags);
static PPathCchCombineEx _PathCchCombineEx;
if (initialized == 0) {
HMODULE pathapi = LoadLibraryExW(L"api-ms-win-core-path-l1-1-0.dll", NULL,
LOAD_LIBRARY_SEARCH_SYSTEM32);
if (pathapi) {
_PathCchCombineEx = (PPathCchCombineEx)GetProcAddress(
pathapi, "PathCchCombineEx");
}
else {
_PathCchCombineEx = NULL;
}
initialized = 1;
}
if (!_PathCchCombineEx) {
return E_NOINTERFACE;
}
return _PathCchCombineEx(buffer, bufsize, dirname, relfile, flags);
}
#endif /* defined(MS_WINDOWS_GAMES) && !defined(MS_WINDOWS_DESKTOP) */
// The caller must ensure "buffer" is big enough.
static int
join_relfile(wchar_t *buffer, size_t bufsize,
const wchar_t *dirname, const wchar_t *relfile)
{
#ifdef MS_WINDOWS
if (FAILED(PathCchCombineEx(buffer, bufsize, dirname, relfile,
PATHCCH_ALLOW_LONG_PATHS))) {
return -1;
}
#else
assert(!_Py_isabs(relfile));
size_t dirlen = wcslen(dirname);
size_t rellen = wcslen(relfile);
size_t maxlen = bufsize - 1;
if (maxlen > MAXPATHLEN || dirlen >= maxlen || rellen >= maxlen - dirlen) {
return -1;
}
if (dirlen == 0) {
// We do not add a leading separator.
wcscpy(buffer, relfile);
}
else {
if (dirname != buffer) {
wcscpy(buffer, dirname);
}
size_t relstart = dirlen;
if (dirlen > 1 && dirname[dirlen - 1] != SEP) {
buffer[dirlen] = SEP;
relstart += 1;
}
wcscpy(&buffer[relstart], relfile);
}
#endif
return 0;
}
/* Join the two paths together, like os.path.join(). Return NULL
if memory could not be allocated. The caller is responsible
for calling PyMem_RawFree() on the result. */
wchar_t *
_Py_join_relfile(const wchar_t *dirname, const wchar_t *relfile)
{
assert(dirname != NULL && relfile != NULL);
#ifndef MS_WINDOWS
assert(!_Py_isabs(relfile));
#endif
size_t maxlen = wcslen(dirname) + 1 + wcslen(relfile);
size_t bufsize = maxlen + 1;
wchar_t *filename = PyMem_RawMalloc(bufsize * sizeof(wchar_t));
if (filename == NULL) {
return NULL;
}
assert(wcslen(dirname) < MAXPATHLEN);
assert(wcslen(relfile) < MAXPATHLEN - wcslen(dirname));
join_relfile(filename, bufsize, dirname, relfile);
return filename;
}
/* Join the two paths together, like os.path.join().
dirname: the target buffer with the dirname already in place,
including trailing NUL
relfile: this must be a relative path
bufsize: total allocated size of the buffer
Return -1 if anything is wrong with the path lengths. */
int
_Py_add_relfile(wchar_t *dirname, const wchar_t *relfile, size_t bufsize)
{
assert(dirname != NULL && relfile != NULL);
assert(bufsize > 0);
return join_relfile(dirname, bufsize, dirname, relfile);
}
size_t
_Py_find_basename(const wchar_t *filename)
{
for (size_t i = wcslen(filename); i > 0; --i) {
if (filename[i] == SEP) {
return i + 1;
}
}
return 0;
}
/* In-place path normalisation. Returns the start of the normalized
path, which will be within the original buffer. Guaranteed to not
make the path longer, and will not fail. 'size' is the length of
the path, if known. If -1, the first null character will be assumed
to be the end of the path. */
wchar_t *
_Py_normpath(wchar_t *path, Py_ssize_t size)
{
if (!path[0] || size == 0) {
return path;
}
wchar_t *pEnd = size >= 0 ? &path[size] : NULL;
wchar_t *p1 = path; // sequentially scanned address in the path
wchar_t *p2 = path; // destination of a scanned character to be ljusted
wchar_t *minP2 = path; // the beginning of the destination range
wchar_t lastC = L'\0'; // the last ljusted character, p2[-1] in most cases
#define IS_END(x) (pEnd ? (x) == pEnd : !*(x))
#ifdef ALTSEP
#define IS_SEP(x) (*(x) == SEP || *(x) == ALTSEP)
#else
#define IS_SEP(x) (*(x) == SEP)
#endif
#define SEP_OR_END(x) (IS_SEP(x) || IS_END(x))
// Skip leading '.\'
if (p1[0] == L'.' && IS_SEP(&p1[1])) {
path = &path[2];
while (IS_SEP(path) && !IS_END(path)) {
path++;
}
p1 = p2 = minP2 = path;
lastC = SEP;
}
#ifdef MS_WINDOWS
// Skip past drive segment and update minP2
else if (p1[0] && p1[1] == L':') {
*p2++ = *p1++;
*p2++ = *p1++;
minP2 = p2;
lastC = L':';
}
// Skip past all \\-prefixed paths, including \\?\, \\.\,
// and network paths, including the first segment.
else if (IS_SEP(&p1[0]) && IS_SEP(&p1[1])) {
int sepCount = 2;
*p2++ = SEP;
*p2++ = SEP;
p1 += 2;
for (; !IS_END(p1) && sepCount; ++p1) {
if (IS_SEP(p1)) {
--sepCount;
*p2++ = lastC = SEP;
} else {
*p2++ = lastC = *p1;
}
}
if (sepCount) {
minP2 = p2; // Invalid path
} else {
minP2 = p2 - 1; // Absolute path has SEP at minP2
}
}
#else
// Skip past two leading SEPs
else if (IS_SEP(&p1[0]) && IS_SEP(&p1[1]) && !IS_SEP(&p1[2])) {
*p2++ = *p1++;
*p2++ = *p1++;
minP2 = p2 - 1; // Absolute path has SEP at minP2
lastC = SEP;
}
#endif /* MS_WINDOWS */
/* if pEnd is specified, check that. Else, check for null terminator */
for (; !IS_END(p1); ++p1) {
wchar_t c = *p1;
#ifdef ALTSEP
if (c == ALTSEP) {
c = SEP;
}
#endif
if (lastC == SEP) {
if (c == L'.') {
int sep_at_1 = SEP_OR_END(&p1[1]);
int sep_at_2 = !sep_at_1 && SEP_OR_END(&p1[2]);
if (sep_at_2 && p1[1] == L'.') {
wchar_t *p3 = p2;
while (p3 != minP2 && *--p3 == SEP) { }
while (p3 != minP2 && *(p3 - 1) != SEP) { --p3; }
if (p2 == minP2
|| (p3[0] == L'.' && p3[1] == L'.' && IS_SEP(&p3[2])))
{
// Previous segment is also ../, so append instead.
// Relative path does not absorb ../ at minP2 as well.
*p2++ = L'.';
*p2++ = L'.';
lastC = L'.';
} else if (p3[0] == SEP) {
// Absolute path, so absorb segment
p2 = p3 + 1;
} else {
p2 = p3;
}
p1 += 1;
} else if (sep_at_1) {
} else {
*p2++ = lastC = c;
}
} else if (c == SEP) {
} else {
*p2++ = lastC = c;
}
} else {
*p2++ = lastC = c;
}
}
*p2 = L'\0';
if (p2 != minP2) {
while (--p2 != minP2 && *p2 == SEP) {
*p2 = L'\0';
}
}
#undef SEP_OR_END
#undef IS_SEP
#undef IS_END
return path;
}
/* Get the current directory. buflen is the buffer size in wide characters
including the null character. Decode the path from the locale encoding.
Return NULL on getcwd() error, on decoding error, or if 'buf' is
too short. */
wchar_t*
_Py_wgetcwd(wchar_t *buf, size_t buflen)
{
#ifdef MS_WINDOWS
int ibuflen = (int)Py_MIN(buflen, INT_MAX);
return _wgetcwd(buf, ibuflen);
#else
char fname[MAXPATHLEN];
wchar_t *wname;
size_t len;
if (getcwd(fname, Py_ARRAY_LENGTH(fname)) == NULL)
return NULL;
wname = Py_DecodeLocale(fname, &len);
if (wname == NULL)
return NULL;
/* wname must have space to store the trailing NUL character */
if (buflen <= len) {
PyMem_RawFree(wname);
return NULL;
}
wcsncpy(buf, wname, buflen);
PyMem_RawFree(wname);
return buf;
#endif
}
/* Duplicate a file descriptor. The new file descriptor is created as
non-inheritable. Return a new file descriptor on success, raise an OSError
exception and return -1 on error.
The GIL is released to call dup(). The caller must hold the GIL. */
int
_Py_dup(int fd)
{
#ifdef MS_WINDOWS
HANDLE handle;
#endif
assert(PyGILState_Check());
#ifdef MS_WINDOWS
handle = _Py_get_osfhandle(fd);
if (handle == INVALID_HANDLE_VALUE)
return -1;
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
fd = dup(fd);
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
if (fd < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
if (_Py_set_inheritable(fd, 0, NULL) < 0) {
_Py_BEGIN_SUPPRESS_IPH
close(fd);
_Py_END_SUPPRESS_IPH
return -1;
}
#elif defined(HAVE_FCNTL_H) && defined(F_DUPFD_CLOEXEC)
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
if (fd < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
#elif HAVE_DUP
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
fd = dup(fd);
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
if (fd < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
if (_Py_set_inheritable(fd, 0, NULL) < 0) {
_Py_BEGIN_SUPPRESS_IPH
close(fd);
_Py_END_SUPPRESS_IPH
return -1;
}
#else
errno = ENOTSUP;
PyErr_SetFromErrno(PyExc_OSError);
return -1;
#endif
return fd;
}
#ifndef MS_WINDOWS
/* Get the blocking mode of the file descriptor.
Return 0 if the O_NONBLOCK flag is set, 1 if the flag is cleared,
raise an exception and return -1 on error. */
int
_Py_get_blocking(int fd)
{
int flags;
_Py_BEGIN_SUPPRESS_IPH
flags = fcntl(fd, F_GETFL, 0);
_Py_END_SUPPRESS_IPH
if (flags < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
return !(flags & O_NONBLOCK);
}
/* Set the blocking mode of the specified file descriptor.
Set the O_NONBLOCK flag if blocking is False, clear the O_NONBLOCK flag
otherwise.
Return 0 on success, raise an exception and return -1 on error. */
int
_Py_set_blocking(int fd, int blocking)
{
/* bpo-41462: On VxWorks, ioctl(FIONBIO) only works on sockets.
Use fcntl() instead. */
#if defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO) && !defined(__VXWORKS__)
int arg = !blocking;
if (ioctl(fd, FIONBIO, &arg) < 0)
goto error;
#else
int flags, res;
_Py_BEGIN_SUPPRESS_IPH
flags = fcntl(fd, F_GETFL, 0);
if (flags >= 0) {
if (blocking)
flags = flags & (~O_NONBLOCK);
else
flags = flags | O_NONBLOCK;
res = fcntl(fd, F_SETFL, flags);
} else {
res = -1;
}
_Py_END_SUPPRESS_IPH
if (res < 0)
goto error;
#endif
return 0;
error:
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
#else /* MS_WINDOWS */
int
_Py_get_blocking(int fd)
{
HANDLE handle;
DWORD mode;
BOOL success;
handle = _Py_get_osfhandle(fd);
if (handle == INVALID_HANDLE_VALUE) {
return -1;
}
Py_BEGIN_ALLOW_THREADS
success = GetNamedPipeHandleStateW(handle, &mode,
NULL, NULL, NULL, NULL, 0);
Py_END_ALLOW_THREADS
if (!success) {
PyErr_SetFromWindowsErr(0);
return -1;
}
return !(mode & PIPE_NOWAIT);
}
int
_Py_set_blocking(int fd, int blocking)
{
HANDLE handle;
DWORD mode;
BOOL success;
handle = _Py_get_osfhandle(fd);
if (handle == INVALID_HANDLE_VALUE) {
return -1;
}
Py_BEGIN_ALLOW_THREADS
success = GetNamedPipeHandleStateW(handle, &mode,
NULL, NULL, NULL, NULL, 0);
if (success) {
if (blocking) {
mode &= ~PIPE_NOWAIT;
}
else {
mode |= PIPE_NOWAIT;
}
success = SetNamedPipeHandleState(handle, &mode, NULL, NULL);
}
Py_END_ALLOW_THREADS
if (!success) {
PyErr_SetFromWindowsErr(0);
return -1;
}
return 0;
}
void*
_Py_get_osfhandle_noraise(int fd)
{
void *handle;
_Py_BEGIN_SUPPRESS_IPH
handle = (void*)_get_osfhandle(fd);
_Py_END_SUPPRESS_IPH
return handle;
}
void*
_Py_get_osfhandle(int fd)
{
void *handle = _Py_get_osfhandle_noraise(fd);
if (handle == INVALID_HANDLE_VALUE)
PyErr_SetFromErrno(PyExc_OSError);
return handle;
}
int
_Py_open_osfhandle_noraise(void *handle, int flags)
{
int fd;
_Py_BEGIN_SUPPRESS_IPH
fd = _open_osfhandle((intptr_t)handle, flags);
_Py_END_SUPPRESS_IPH
return fd;
}
int
_Py_open_osfhandle(void *handle, int flags)
{
int fd = _Py_open_osfhandle_noraise(handle, flags);
if (fd == -1)
PyErr_SetFromErrno(PyExc_OSError);
return fd;
}
#endif /* MS_WINDOWS */
int
_Py_GetLocaleconvNumeric(struct lconv *lc,
PyObject **decimal_point, PyObject **thousands_sep)
{
assert(decimal_point != NULL);
assert(thousands_sep != NULL);
#ifndef MS_WINDOWS
int change_locale = 0;
if ((strlen(lc->decimal_point) > 1 || ((unsigned char)lc->decimal_point[0]) > 127)) {
change_locale = 1;
}
if ((strlen(lc->thousands_sep) > 1 || ((unsigned char)lc->thousands_sep[0]) > 127)) {
change_locale = 1;
}
/* Keep a copy of the LC_CTYPE locale */
char *oldloc = NULL, *loc = NULL;
if (change_locale) {
oldloc = setlocale(LC_CTYPE, NULL);
if (!oldloc) {
PyErr_SetString(PyExc_RuntimeWarning,
"failed to get LC_CTYPE locale");
return -1;
}
oldloc = _PyMem_Strdup(oldloc);
if (!oldloc) {
PyErr_NoMemory();
return -1;
}
loc = setlocale(LC_NUMERIC, NULL);
if (loc != NULL && strcmp(loc, oldloc) == 0) {
loc = NULL;
}
if (loc != NULL) {
/* Only set the locale temporarily the LC_CTYPE locale
if LC_NUMERIC locale is different than LC_CTYPE locale and
decimal_point and/or thousands_sep are non-ASCII or longer than
1 byte */
setlocale(LC_CTYPE, loc);
}
}
#define GET_LOCALE_STRING(ATTR) PyUnicode_DecodeLocale(lc->ATTR, NULL)
#else /* MS_WINDOWS */
/* Use _W_* fields of Windows strcut lconv */
#define GET_LOCALE_STRING(ATTR) PyUnicode_FromWideChar(lc->_W_ ## ATTR, -1)
#endif /* MS_WINDOWS */
int res = -1;
*decimal_point = GET_LOCALE_STRING(decimal_point);
if (*decimal_point == NULL) {
goto done;
}
*thousands_sep = GET_LOCALE_STRING(thousands_sep);
if (*thousands_sep == NULL) {
goto done;
}
res = 0;
done:
#ifndef MS_WINDOWS
if (loc != NULL) {
setlocale(LC_CTYPE, oldloc);
}
PyMem_Free(oldloc);
#endif
return res;
#undef GET_LOCALE_STRING
}
/* Our selection logic for which function to use is as follows:
* 1. If close_range(2) is available, always prefer that; it's better for
* contiguous ranges like this than fdwalk(3) which entails iterating over
* the entire fd space and simply doing nothing for those outside the range.
* 2. If closefrom(2) is available, we'll attempt to use that next if we're
* closing up to sysconf(_SC_OPEN_MAX).
* 2a. Fallback to fdwalk(3) if we're not closing up to sysconf(_SC_OPEN_MAX),
* as that will be more performant if the range happens to have any chunk of
* non-opened fd in the middle.
* 2b. If fdwalk(3) isn't available, just do a plain close(2) loop.
*/
#ifdef __FreeBSD__
# define USE_CLOSEFROM
#endif /* __FreeBSD__ */
#ifdef HAVE_FDWALK
# define USE_FDWALK
#endif /* HAVE_FDWALK */
#ifdef USE_FDWALK
static int
_fdwalk_close_func(void *lohi, int fd)
{
int lo = ((int *)lohi)[0];
int hi = ((int *)lohi)[1];
if (fd >= hi) {
return 1;
}
else if (fd >= lo) {
/* Ignore errors */
(void)close(fd);
}
return 0;
}
#endif /* USE_FDWALK */
/* Closes all file descriptors in [first, last], ignoring errors. */
void
_Py_closerange(int first, int last)
{
first = Py_MAX(first, 0);
_Py_BEGIN_SUPPRESS_IPH
#ifdef HAVE_CLOSE_RANGE
if (close_range(first, last, 0) == 0) {
/* close_range() ignores errors when it closes file descriptors.
* Possible reasons of an error return are lack of kernel support
* or denial of the underlying syscall by a seccomp sandbox on Linux.
* Fallback to other methods in case of any error. */
}
else
#endif /* HAVE_CLOSE_RANGE */
#ifdef USE_CLOSEFROM
if (last >= sysconf(_SC_OPEN_MAX)) {
/* Any errors encountered while closing file descriptors are ignored */
closefrom(first);
}
else
#endif /* USE_CLOSEFROM */
#ifdef USE_FDWALK
{
int lohi[2];
lohi[0] = first;
lohi[1] = last + 1;
fdwalk(_fdwalk_close_func, lohi);
}
#else
{
for (int i = first; i <= last; i++) {
/* Ignore errors */
(void)close(i);
}
}
#endif /* USE_FDWALK */
_Py_END_SUPPRESS_IPH
}
|