forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsysmodule.c
2508 lines (2214 loc) · 72.2 KB
/
sysmodule.c
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
/* 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 "code.h"
#include "frameobject.h"
#include "pythread.h"
#include "osdefs.h"
#include <locale.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
_Py_IDENTIFIER(_);
_Py_IDENTIFIER(__sizeof__);
_Py_IDENTIFIER(buffer);
_Py_IDENTIFIER(builtins);
_Py_IDENTIFIER(encoding);
_Py_IDENTIFIER(path);
_Py_IDENTIFIER(stdout);
_Py_IDENTIFIER(stderr);
_Py_IDENTIFIER(write);
PyObject *
_PySys_GetObjectId(_Py_Identifier *key)
{
PyThreadState *tstate = PyThreadState_GET();
PyObject *sd = tstate->interp->sysdict;
if (sd == NULL)
return NULL;
return _PyDict_GetItemId(sd, key);
}
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_SetObjectId(_Py_Identifier *key, PyObject *v)
{
PyThreadState *tstate = PyThreadState_GET();
PyObject *sd = tstate->interp->sysdict;
if (v == NULL) {
if (_PyDict_GetItemId(sd, key) == NULL)
return 0;
else
return _PyDict_DelItemId(sd, key);
}
else
return _PyDict_SetItemId(sd, key, v);
}
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);
}
/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
error handler. If sys.stdout has a buffer attribute, use
sys.stdout.buffer.write(encoded), otherwise redecode the string and use
sys.stdout.write(redecoded).
Helper function for sys_displayhook(). */
static int
sys_displayhook_unencodable(PyObject *outf, PyObject *o)
{
PyObject *stdout_encoding = NULL;
PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
const char *stdout_encoding_str;
int ret;
stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
if (stdout_encoding == NULL)
goto error;
stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
if (stdout_encoding_str == NULL)
goto error;
repr_str = PyObject_Repr(o);
if (repr_str == NULL)
goto error;
encoded = PyUnicode_AsEncodedString(repr_str,
stdout_encoding_str,
"backslashreplace");
Py_DECREF(repr_str);
if (encoded == NULL)
goto error;
buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
if (buffer) {
result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Py_DECREF(buffer);
Py_DECREF(encoded);
if (result == NULL)
goto error;
Py_DECREF(result);
}
else {
PyErr_Clear();
escaped_str = PyUnicode_FromEncodedObject(encoded,
stdout_encoding_str,
"strict");
Py_DECREF(encoded);
if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
Py_DECREF(escaped_str);
goto error;
}
Py_DECREF(escaped_str);
}
ret = 0;
goto finally;
error:
ret = -1;
finally:
Py_XDECREF(stdout_encoding);
return ret;
}
static PyObject *
sys_displayhook(PyObject *self, PyObject *o)
{
PyObject *outf;
PyInterpreterState *interp = PyThreadState_GET()->interp;
PyObject *modules = interp->modules;
PyObject *builtins;
static PyObject *newline = NULL;
int err;
builtins = _PyDict_GetItemId(modules, &PyId_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_RETURN_NONE;
}
if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
return NULL;
outf = _PySys_GetObjectId(&PyId_stdout);
if (outf == NULL || outf == Py_None) {
PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
return NULL;
}
if (PyFile_WriteObject(o, outf, 0) != 0) {
if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
/* repr(o) is not encodable to sys.stdout.encoding with
* sys.stdout.errors error handler (which is probably 'strict') */
PyErr_Clear();
err = sys_displayhook_unencodable(outf, o);
if (err)
return NULL;
}
else {
return NULL;
}
}
if (newline == NULL) {
newline = PyUnicode_FromString("\n");
if (newline == NULL)
return NULL;
}
if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
return NULL;
if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
return NULL;
Py_RETURN_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_RETURN_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 an integer, 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_getfilesystemencoding(PyObject *self)
{
if (Py_FileSystemDefaultEncoding)
return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
PyErr_SetString(PyExc_RuntimeError,
"filesystem encoding is not initialized");
return NULL;
}
PyDoc_STRVAR(getfilesystemencoding_doc,
"getfilesystemencoding() -> string\n\
\n\
Return the encoding used to convert Unicode filenames in\n\
operating system filenames."
);
static PyObject *
sys_getfilesystemencodeerrors(PyObject *self)
{
if (Py_FileSystemDefaultEncodeErrors)
return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors);
PyErr_SetString(PyExc_RuntimeError,
"filesystem encoding is not initialized");
return NULL;
}
PyDoc_STRVAR(getfilesystemencodeerrors_doc,
"getfilesystemencodeerrors() -> string\n\
\n\
Return the error mode 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 const char * const 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(PyObject* callback,
PyFrameObject *frame, int what, PyObject *arg)
{
PyObject *result;
PyObject *stack[3];
if (PyFrame_FastToLocalsWithError(frame) < 0) {
return NULL;
}
stack[0] = (PyObject *)frame;
stack[1] = whatstrings[what];
stack[2] = (arg != NULL) ? arg : Py_None;
/* call the Python-level function */
result = _PyObject_FastCall(callback, stack, 3);
PyFrame_LocalsToFast(frame, 1);
if (result == NULL) {
PyTraceBack_Here(frame);
}
return result;
}
static int
profile_trampoline(PyObject *self, PyFrameObject *frame,
int what, PyObject *arg)
{
PyObject *result;
if (arg == NULL)
arg = Py_None;
result = call_trampoline(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)
{
PyObject *callback;
PyObject *result;
if (what == PyTrace_CALL)
callback = self;
else
callback = frame->f_trace;
if (callback == NULL)
return 0;
result = call_trampoline(callback, frame, what, arg);
if (result == NULL) {
PyEval_SetTrace(NULL, NULL);
Py_CLEAR(frame->f_trace);
return -1;
}
if (result != Py_None) {
Py_XSETREF(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_RETURN_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_RETURN_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 int _check_interval = 100;
static PyObject *
sys_setcheckinterval(PyObject *self, PyObject *args)
{
if (PyErr_WarnEx(PyExc_DeprecationWarning,
"sys.getcheckinterval() and sys.setcheckinterval() "
"are deprecated. Use sys.setswitchinterval() "
"instead.", 1) < 0)
return NULL;
if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
return NULL;
Py_RETURN_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)
{
if (PyErr_WarnEx(PyExc_DeprecationWarning,
"sys.getcheckinterval() and sys.setcheckinterval() "
"are deprecated. Use sys.getswitchinterval() "
"instead.", 1) < 0)
return NULL;
return PyLong_FromLong(_check_interval);
}
PyDoc_STRVAR(getcheckinterval_doc,
"getcheckinterval() -> current check interval; see setcheckinterval()."
);
#ifdef WITH_THREAD
static PyObject *
sys_setswitchinterval(PyObject *self, PyObject *args)
{
double d;
if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
return NULL;
if (d <= 0.0) {
PyErr_SetString(PyExc_ValueError,
"switch interval must be strictly positive");
return NULL;
}
_PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Py_RETURN_NONE;
}
PyDoc_STRVAR(setswitchinterval_doc,
"setswitchinterval(n)\n\
\n\
Set the ideal thread switching delay inside the Python interpreter\n\
The actual frequency of switching threads can be lower if the\n\
interpreter executes long sequences of uninterruptible code\n\
(this is implementation-specific and workload-dependent).\n\
\n\
The parameter must represent the desired switching delay in seconds\n\
A typical value is 0.005 (5 milliseconds)."
);
static PyObject *
sys_getswitchinterval(PyObject *self, PyObject *args)
{
return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
}
PyDoc_STRVAR(getswitchinterval_doc,
"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
);
#endif /* WITH_THREAD */
static PyObject *
sys_setrecursionlimit(PyObject *self, PyObject *args)
{
int new_limit, mark;
PyThreadState *tstate;
if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
return NULL;
if (new_limit < 1) {
PyErr_SetString(PyExc_ValueError,
"recursion limit must be greater or equal than 1");
return NULL;
}
/* Issue #25274: When the recursion depth hits the recursion limit in
_Py_CheckRecursiveCall(), the overflowed flag of the thread state is
set to 1 and a RecursionError is raised. The overflowed flag is reset
to 0 when the recursion depth goes below the low-water mark: see
Py_LeaveRecursiveCall().
Reject too low new limit if the current recursion depth is higher than
the new low-water mark. Otherwise it may not be possible anymore to
reset the overflowed flag to 0. */
mark = _Py_RecursionLimitLowerWaterMark(new_limit);
tstate = PyThreadState_GET();
if (tstate->recursion_depth >= mark) {
PyErr_Format(PyExc_RecursionError,
"cannot set the recursion limit to %i at "
"the recursion depth %i: the limit is too low",
new_limit, tstate->recursion_depth);
return NULL;
}
Py_SetRecursionLimit(new_limit);
Py_RETURN_NONE;
}
static PyObject *
sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
{
if (wrapper != Py_None) {
if (!PyCallable_Check(wrapper)) {
PyErr_Format(PyExc_TypeError,
"callable expected, got %.50s",
Py_TYPE(wrapper)->tp_name);
return NULL;
}
_PyEval_SetCoroutineWrapper(wrapper);
}
else {
_PyEval_SetCoroutineWrapper(NULL);
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(set_coroutine_wrapper_doc,
"set_coroutine_wrapper(wrapper)\n\
\n\
Set a wrapper for coroutine objects."
);
static PyObject *
sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
{
PyObject *wrapper = _PyEval_GetCoroutineWrapper();
if (wrapper == NULL) {
wrapper = Py_None;
}
Py_INCREF(wrapper);
return wrapper;
}
PyDoc_STRVAR(get_coroutine_wrapper_doc,
"get_coroutine_wrapper()\n\
\n\
Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
);
static PyTypeObject AsyncGenHooksType;
PyDoc_STRVAR(asyncgen_hooks_doc,
"asyncgen_hooks\n\
\n\
A struct sequence providing information about asynhronous\n\
generators hooks. The attributes are read only.");
static PyStructSequence_Field asyncgen_hooks_fields[] = {
{"firstiter", "Hook to intercept first iteration"},
{"finalizer", "Hook to intercept finalization"},
{0}
};
static PyStructSequence_Desc asyncgen_hooks_desc = {
"asyncgen_hooks", /* name */
asyncgen_hooks_doc, /* doc */
asyncgen_hooks_fields , /* fields */
2
};
static PyObject *
sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
{
static char *keywords[] = {"firstiter", "finalizer", NULL};
PyObject *firstiter = NULL;
PyObject *finalizer = NULL;
if (!PyArg_ParseTupleAndKeywords(
args, kw, "|OO", keywords,
&firstiter, &finalizer)) {
return NULL;
}
if (finalizer && finalizer != Py_None) {
if (!PyCallable_Check(finalizer)) {
PyErr_Format(PyExc_TypeError,
"callable finalizer expected, got %.50s",
Py_TYPE(finalizer)->tp_name);
return NULL;
}
_PyEval_SetAsyncGenFinalizer(finalizer);
}
else if (finalizer == Py_None) {
_PyEval_SetAsyncGenFinalizer(NULL);
}
if (firstiter && firstiter != Py_None) {
if (!PyCallable_Check(firstiter)) {
PyErr_Format(PyExc_TypeError,
"callable firstiter expected, got %.50s",
Py_TYPE(firstiter)->tp_name);
return NULL;
}
_PyEval_SetAsyncGenFirstiter(firstiter);
}
else if (firstiter == Py_None) {
_PyEval_SetAsyncGenFirstiter(NULL);
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(set_asyncgen_hooks_doc,
"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
\n\
Set a finalizer for async generators objects."
);
static PyObject *
sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
{
PyObject *res;
PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
res = PyStructSequence_New(&AsyncGenHooksType);
if (res == NULL) {
return NULL;
}
if (firstiter == NULL) {
firstiter = Py_None;
}
if (finalizer == NULL) {
finalizer = Py_None;
}
Py_INCREF(firstiter);
PyStructSequence_SET_ITEM(res, 0, firstiter);
Py_INCREF(finalizer);
PyStructSequence_SET_ITEM(res, 1, finalizer);
return res;
}
PyDoc_STRVAR(get_asyncgen_hooks_doc,
"get_asyncgen_hooks()\n\
\n\
Return a namedtuple of installed asynchronous generators hooks \
(firstiter, finalizer)."
);
static PyTypeObject Hash_InfoType;
PyDoc_STRVAR(hash_info_doc,
"hash_info\n\
\n\
A struct sequence providing parameters used for computing\n\
hashes. The attributes are read only.");
static PyStructSequence_Field hash_info_fields[] = {
{"width", "width of the type used for hashing, in bits"},
{"modulus", "prime number giving the modulus on which the hash "
"function is based"},
{"inf", "value to be used for hash of a positive infinity"},
{"nan", "value to be used for hash of a nan"},
{"imag", "multiplier used for the imaginary part of a complex number"},
{"algorithm", "name of the algorithm for hashing of str, bytes and "
"memoryviews"},
{"hash_bits", "internal output size of hash algorithm"},
{"seed_bits", "seed size of hash algorithm"},
{"cutoff", "small string optimization cutoff"},
{NULL, NULL}
};
static PyStructSequence_Desc hash_info_desc = {
"sys.hash_info",
hash_info_doc,
hash_info_fields,
9,
};
static PyObject *
get_hash_info(void)
{
PyObject *hash_info;
int field = 0;
PyHash_FuncDef *hashfunc;
hash_info = PyStructSequence_New(&Hash_InfoType);
if (hash_info == NULL)
return NULL;
hashfunc = PyHash_GetFuncDef();
PyStructSequence_SET_ITEM(hash_info, field++,
PyLong_FromLong(8*sizeof(Py_hash_t)));
PyStructSequence_SET_ITEM(hash_info, field++,
PyLong_FromSsize_t(_PyHASH_MODULUS));
PyStructSequence_SET_ITEM(hash_info, field++,
PyLong_FromLong(_PyHASH_INF));
PyStructSequence_SET_ITEM(hash_info, field++,
PyLong_FromLong(_PyHASH_NAN));
PyStructSequence_SET_ITEM(hash_info, field++,
PyLong_FromLong(_PyHASH_IMAG));
PyStructSequence_SET_ITEM(hash_info, field++,
PyUnicode_FromString(hashfunc->name));
PyStructSequence_SET_ITEM(hash_info, field++,
PyLong_FromLong(hashfunc->hash_bits));
PyStructSequence_SET_ITEM(hash_info, field++,
PyLong_FromLong(hashfunc->seed_bits));
PyStructSequence_SET_ITEM(hash_info, field++,
PyLong_FromLong(Py_HASH_CUTOFF));
if (PyErr_Occurred()) {
Py_CLEAR(hash_info);
return NULL;
}
return hash_info;
}
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 as a named tuple.\n\
The members are named: major, minor, build, platform, service_pack,\n\
service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
backward compatibility, only the first 5 items are available by indexing.\n\
All elements are numbers, except service_pack and platform_type which are\n\
strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
server. Platform_version is a 3-tuple containing a version number that is\n\
intended for identifying the OS rather than feature detection."
);
static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
static PyStructSequence_Field windows_version_fields[] = {
{"major", "Major version number"},
{"minor", "Minor version number"},
{"build", "Build number"},
{"platform", "Operating system platform"},
{"service_pack", "Latest Service Pack installed on the system"},
{"service_pack_major", "Service Pack major version number"},
{"service_pack_minor", "Service Pack minor version number"},
{"suite_mask", "Bit mask identifying available product suites"},
{"product_type", "System product type"},
{"platform_version", "Diagnostic version number"},
{0}
};
static PyStructSequence_Desc windows_version_desc = {
"sys.getwindowsversion", /* name */
getwindowsversion_doc, /* doc */
windows_version_fields, /* fields */
5 /* For backward compatibility,
only the first 5 items are accessible
via indexing, the rest are name only */
};
/* Disable deprecation warnings about GetVersionEx as the result is
being passed straight through to the caller, who is responsible for
using it correctly. */
#pragma warning(push)
#pragma warning(disable:4996)
static PyObject *
sys_getwindowsversion(PyObject *self)
{
PyObject *version;
int pos = 0;
OSVERSIONINFOEX ver;
DWORD realMajor, realMinor, realBuild;
HANDLE hKernel32;
wchar_t kernel32_path[MAX_PATH];
LPVOID verblock;
DWORD verblock_size;
ver.dwOSVersionInfoSize = sizeof(ver);
if (!GetVersionEx((OSVERSIONINFO*) &ver))
return PyErr_SetFromWindowsErr(0);
version = PyStructSequence_New(&WindowsVersionType);
if (version == NULL)
return NULL;
PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
realMajor = ver.dwMajorVersion;
realMinor = ver.dwMinorVersion;
realBuild = ver.dwBuildNumber;
// GetVersion will lie if we are running in a compatibility mode.
// We need to read the version info from a system file resource
// to accurately identify the OS version. If we fail for any reason,
// just return whatever GetVersion said.
hKernel32 = GetModuleHandleW(L"kernel32.dll");
if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
(verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
(verblock = PyMem_RawMalloc(verblock_size))) {
VS_FIXEDFILEINFO *ffi;
UINT ffi_len;
if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
realMajor = HIWORD(ffi->dwProductVersionMS);
realMinor = LOWORD(ffi->dwProductVersionMS);
realBuild = HIWORD(ffi->dwProductVersionLS);
}
PyMem_RawFree(verblock);
}
PyStructSequence_SET_ITEM(version, pos++, PyTuple_Pack(3,
PyLong_FromLong(realMajor),
PyLong_FromLong(realMinor),
PyLong_FromLong(realBuild)
));
if (PyErr_Occurred()) {
Py_DECREF(version);
return NULL;
}
return version;
}
#pragma warning(pop)
PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
"_enablelegacywindowsfsencoding()\n\
\n\
Changes the default filesystem encoding to mbcs:replace for consistency\n\
with earlier versions of Python. See PEP 529 for more information.\n\
\n\
This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
environment variable before launching Python."
);