ยปCore Development>Code coverage>Python/sysmodule.c

Python code coverage for Python/sysmodule.c

#countcontent
1n/a
2n/a/* System module */
3n/a
4n/a/*
5n/aVarious bits of information used by the interpreter are collected in
6n/amodule 'sys'.
7n/aFunction member:
8n/a- exit(sts): raise SystemExit
9n/aData members:
10n/a- stdin, stdout, stderr: standard file objects
11n/a- modules: the table of modules (dictionary)
12n/a- path: module search path (list of strings)
13n/a- argv: script arguments (list of strings)
14n/a- ps1, ps2: optional primary and secondary prompts (strings)
15n/a*/
16n/a
17n/a#include "Python.h"
18n/a#include "code.h"
19n/a#include "frameobject.h"
20n/a#include "pythread.h"
21n/a
22n/a#include "osdefs.h"
23n/a#include <locale.h>
24n/a
25n/a#ifdef MS_WINDOWS
26n/a#define WIN32_LEAN_AND_MEAN
27n/a#include <windows.h>
28n/a#endif /* MS_WINDOWS */
29n/a
30n/a#ifdef MS_COREDLL
31n/aextern void *PyWin_DLLhModule;
32n/a/* A string loaded from the DLL at startup: */
33n/aextern const char *PyWin_DLLVersionString;
34n/a#endif
35n/a
36n/a#ifdef HAVE_LANGINFO_H
37n/a#include <langinfo.h>
38n/a#endif
39n/a
40n/a_Py_IDENTIFIER(_);
41n/a_Py_IDENTIFIER(__sizeof__);
42n/a_Py_IDENTIFIER(buffer);
43n/a_Py_IDENTIFIER(builtins);
44n/a_Py_IDENTIFIER(encoding);
45n/a_Py_IDENTIFIER(path);
46n/a_Py_IDENTIFIER(stdout);
47n/a_Py_IDENTIFIER(stderr);
48n/a_Py_IDENTIFIER(write);
49n/a
50n/aPyObject *
51n/a_PySys_GetObjectId(_Py_Identifier *key)
52n/a{
53n/a PyThreadState *tstate = PyThreadState_GET();
54n/a PyObject *sd = tstate->interp->sysdict;
55n/a if (sd == NULL)
56n/a return NULL;
57n/a return _PyDict_GetItemId(sd, key);
58n/a}
59n/a
60n/aPyObject *
61n/aPySys_GetObject(const char *name)
62n/a{
63n/a PyThreadState *tstate = PyThreadState_GET();
64n/a PyObject *sd = tstate->interp->sysdict;
65n/a if (sd == NULL)
66n/a return NULL;
67n/a return PyDict_GetItemString(sd, name);
68n/a}
69n/a
70n/aint
71n/a_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
72n/a{
73n/a PyThreadState *tstate = PyThreadState_GET();
74n/a PyObject *sd = tstate->interp->sysdict;
75n/a if (v == NULL) {
76n/a if (_PyDict_GetItemId(sd, key) == NULL)
77n/a return 0;
78n/a else
79n/a return _PyDict_DelItemId(sd, key);
80n/a }
81n/a else
82n/a return _PyDict_SetItemId(sd, key, v);
83n/a}
84n/a
85n/aint
86n/aPySys_SetObject(const char *name, PyObject *v)
87n/a{
88n/a PyThreadState *tstate = PyThreadState_GET();
89n/a PyObject *sd = tstate->interp->sysdict;
90n/a if (v == NULL) {
91n/a if (PyDict_GetItemString(sd, name) == NULL)
92n/a return 0;
93n/a else
94n/a return PyDict_DelItemString(sd, name);
95n/a }
96n/a else
97n/a return PyDict_SetItemString(sd, name, v);
98n/a}
99n/a
100n/a/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
101n/a error handler. If sys.stdout has a buffer attribute, use
102n/a sys.stdout.buffer.write(encoded), otherwise redecode the string and use
103n/a sys.stdout.write(redecoded).
104n/a
105n/a Helper function for sys_displayhook(). */
106n/astatic int
107n/asys_displayhook_unencodable(PyObject *outf, PyObject *o)
108n/a{
109n/a PyObject *stdout_encoding = NULL;
110n/a PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
111n/a const char *stdout_encoding_str;
112n/a int ret;
113n/a
114n/a stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
115n/a if (stdout_encoding == NULL)
116n/a goto error;
117n/a stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
118n/a if (stdout_encoding_str == NULL)
119n/a goto error;
120n/a
121n/a repr_str = PyObject_Repr(o);
122n/a if (repr_str == NULL)
123n/a goto error;
124n/a encoded = PyUnicode_AsEncodedString(repr_str,
125n/a stdout_encoding_str,
126n/a "backslashreplace");
127n/a Py_DECREF(repr_str);
128n/a if (encoded == NULL)
129n/a goto error;
130n/a
131n/a buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
132n/a if (buffer) {
133n/a result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
134n/a Py_DECREF(buffer);
135n/a Py_DECREF(encoded);
136n/a if (result == NULL)
137n/a goto error;
138n/a Py_DECREF(result);
139n/a }
140n/a else {
141n/a PyErr_Clear();
142n/a escaped_str = PyUnicode_FromEncodedObject(encoded,
143n/a stdout_encoding_str,
144n/a "strict");
145n/a Py_DECREF(encoded);
146n/a if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
147n/a Py_DECREF(escaped_str);
148n/a goto error;
149n/a }
150n/a Py_DECREF(escaped_str);
151n/a }
152n/a ret = 0;
153n/a goto finally;
154n/a
155n/aerror:
156n/a ret = -1;
157n/afinally:
158n/a Py_XDECREF(stdout_encoding);
159n/a return ret;
160n/a}
161n/a
162n/astatic PyObject *
163n/asys_displayhook(PyObject *self, PyObject *o)
164n/a{
165n/a PyObject *outf;
166n/a PyInterpreterState *interp = PyThreadState_GET()->interp;
167n/a PyObject *modules = interp->modules;
168n/a PyObject *builtins;
169n/a static PyObject *newline = NULL;
170n/a int err;
171n/a
172n/a builtins = _PyDict_GetItemId(modules, &PyId_builtins);
173n/a if (builtins == NULL) {
174n/a PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
175n/a return NULL;
176n/a }
177n/a
178n/a /* Print value except if None */
179n/a /* After printing, also assign to '_' */
180n/a /* Before, set '_' to None to avoid recursion */
181n/a if (o == Py_None) {
182n/a Py_RETURN_NONE;
183n/a }
184n/a if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
185n/a return NULL;
186n/a outf = _PySys_GetObjectId(&PyId_stdout);
187n/a if (outf == NULL || outf == Py_None) {
188n/a PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
189n/a return NULL;
190n/a }
191n/a if (PyFile_WriteObject(o, outf, 0) != 0) {
192n/a if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
193n/a /* repr(o) is not encodable to sys.stdout.encoding with
194n/a * sys.stdout.errors error handler (which is probably 'strict') */
195n/a PyErr_Clear();
196n/a err = sys_displayhook_unencodable(outf, o);
197n/a if (err)
198n/a return NULL;
199n/a }
200n/a else {
201n/a return NULL;
202n/a }
203n/a }
204n/a if (newline == NULL) {
205n/a newline = PyUnicode_FromString("\n");
206n/a if (newline == NULL)
207n/a return NULL;
208n/a }
209n/a if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
210n/a return NULL;
211n/a if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
212n/a return NULL;
213n/a Py_RETURN_NONE;
214n/a}
215n/a
216n/aPyDoc_STRVAR(displayhook_doc,
217n/a"displayhook(object) -> None\n"
218n/a"\n"
219n/a"Print an object to sys.stdout and also save it in builtins._\n"
220n/a);
221n/a
222n/astatic PyObject *
223n/asys_excepthook(PyObject* self, PyObject* args)
224n/a{
225n/a PyObject *exc, *value, *tb;
226n/a if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
227n/a return NULL;
228n/a PyErr_Display(exc, value, tb);
229n/a Py_RETURN_NONE;
230n/a}
231n/a
232n/aPyDoc_STRVAR(excepthook_doc,
233n/a"excepthook(exctype, value, traceback) -> None\n"
234n/a"\n"
235n/a"Handle an exception by displaying it with a traceback on sys.stderr.\n"
236n/a);
237n/a
238n/astatic PyObject *
239n/asys_exc_info(PyObject *self, PyObject *noargs)
240n/a{
241n/a PyThreadState *tstate;
242n/a tstate = PyThreadState_GET();
243n/a return Py_BuildValue(
244n/a "(OOO)",
245n/a tstate->exc_type != NULL ? tstate->exc_type : Py_None,
246n/a tstate->exc_value != NULL ? tstate->exc_value : Py_None,
247n/a tstate->exc_traceback != NULL ?
248n/a tstate->exc_traceback : Py_None);
249n/a}
250n/a
251n/aPyDoc_STRVAR(exc_info_doc,
252n/a"exc_info() -> (type, value, traceback)\n\
253n/a\n\
254n/aReturn information about the most recent exception caught by an except\n\
255n/aclause in the current stack frame or in an older stack frame."
256n/a);
257n/a
258n/astatic PyObject *
259n/asys_exit(PyObject *self, PyObject *args)
260n/a{
261n/a PyObject *exit_code = 0;
262n/a if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
263n/a return NULL;
264n/a /* Raise SystemExit so callers may catch it or clean up. */
265n/a PyErr_SetObject(PyExc_SystemExit, exit_code);
266n/a return NULL;
267n/a}
268n/a
269n/aPyDoc_STRVAR(exit_doc,
270n/a"exit([status])\n\
271n/a\n\
272n/aExit the interpreter by raising SystemExit(status).\n\
273n/aIf the status is omitted or None, it defaults to zero (i.e., success).\n\
274n/aIf the status is an integer, it will be used as the system exit status.\n\
275n/aIf it is another kind of object, it will be printed and the system\n\
276n/aexit status will be one (i.e., failure)."
277n/a);
278n/a
279n/a
280n/astatic PyObject *
281n/asys_getdefaultencoding(PyObject *self)
282n/a{
283n/a return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
284n/a}
285n/a
286n/aPyDoc_STRVAR(getdefaultencoding_doc,
287n/a"getdefaultencoding() -> string\n\
288n/a\n\
289n/aReturn the current default string encoding used by the Unicode \n\
290n/aimplementation."
291n/a);
292n/a
293n/astatic PyObject *
294n/asys_getfilesystemencoding(PyObject *self)
295n/a{
296n/a if (Py_FileSystemDefaultEncoding)
297n/a return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
298n/a PyErr_SetString(PyExc_RuntimeError,
299n/a "filesystem encoding is not initialized");
300n/a return NULL;
301n/a}
302n/a
303n/aPyDoc_STRVAR(getfilesystemencoding_doc,
304n/a"getfilesystemencoding() -> string\n\
305n/a\n\
306n/aReturn the encoding used to convert Unicode filenames in\n\
307n/aoperating system filenames."
308n/a);
309n/a
310n/astatic PyObject *
311n/asys_getfilesystemencodeerrors(PyObject *self)
312n/a{
313n/a if (Py_FileSystemDefaultEncodeErrors)
314n/a return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors);
315n/a PyErr_SetString(PyExc_RuntimeError,
316n/a "filesystem encoding is not initialized");
317n/a return NULL;
318n/a}
319n/a
320n/aPyDoc_STRVAR(getfilesystemencodeerrors_doc,
321n/a "getfilesystemencodeerrors() -> string\n\
322n/a\n\
323n/aReturn the error mode used to convert Unicode filenames in\n\
324n/aoperating system filenames."
325n/a);
326n/a
327n/astatic PyObject *
328n/asys_intern(PyObject *self, PyObject *args)
329n/a{
330n/a PyObject *s;
331n/a if (!PyArg_ParseTuple(args, "U:intern", &s))
332n/a return NULL;
333n/a if (PyUnicode_CheckExact(s)) {
334n/a Py_INCREF(s);
335n/a PyUnicode_InternInPlace(&s);
336n/a return s;
337n/a }
338n/a else {
339n/a PyErr_Format(PyExc_TypeError,
340n/a "can't intern %.400s", s->ob_type->tp_name);
341n/a return NULL;
342n/a }
343n/a}
344n/a
345n/aPyDoc_STRVAR(intern_doc,
346n/a"intern(string) -> string\n\
347n/a\n\
348n/a``Intern'' the given string. This enters the string in the (global)\n\
349n/atable of interned strings whose purpose is to speed up dictionary lookups.\n\
350n/aReturn the string itself or the previously interned string object with the\n\
351n/asame value.");
352n/a
353n/a
354n/a/*
355n/a * Cached interned string objects used for calling the profile and
356n/a * trace functions. Initialized by trace_init().
357n/a */
358n/astatic PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
359n/a
360n/astatic int
361n/atrace_init(void)
362n/a{
363n/a static const char * const whatnames[7] = {
364n/a "call", "exception", "line", "return",
365n/a "c_call", "c_exception", "c_return"
366n/a };
367n/a PyObject *name;
368n/a int i;
369n/a for (i = 0; i < 7; ++i) {
370n/a if (whatstrings[i] == NULL) {
371n/a name = PyUnicode_InternFromString(whatnames[i]);
372n/a if (name == NULL)
373n/a return -1;
374n/a whatstrings[i] = name;
375n/a }
376n/a }
377n/a return 0;
378n/a}
379n/a
380n/a
381n/astatic PyObject *
382n/acall_trampoline(PyObject* callback,
383n/a PyFrameObject *frame, int what, PyObject *arg)
384n/a{
385n/a PyObject *result;
386n/a PyObject *stack[3];
387n/a
388n/a if (PyFrame_FastToLocalsWithError(frame) < 0) {
389n/a return NULL;
390n/a }
391n/a
392n/a stack[0] = (PyObject *)frame;
393n/a stack[1] = whatstrings[what];
394n/a stack[2] = (arg != NULL) ? arg : Py_None;
395n/a
396n/a /* call the Python-level function */
397n/a result = _PyObject_FastCall(callback, stack, 3);
398n/a
399n/a PyFrame_LocalsToFast(frame, 1);
400n/a if (result == NULL) {
401n/a PyTraceBack_Here(frame);
402n/a }
403n/a
404n/a return result;
405n/a}
406n/a
407n/astatic int
408n/aprofile_trampoline(PyObject *self, PyFrameObject *frame,
409n/a int what, PyObject *arg)
410n/a{
411n/a PyObject *result;
412n/a
413n/a if (arg == NULL)
414n/a arg = Py_None;
415n/a result = call_trampoline(self, frame, what, arg);
416n/a if (result == NULL) {
417n/a PyEval_SetProfile(NULL, NULL);
418n/a return -1;
419n/a }
420n/a Py_DECREF(result);
421n/a return 0;
422n/a}
423n/a
424n/astatic int
425n/atrace_trampoline(PyObject *self, PyFrameObject *frame,
426n/a int what, PyObject *arg)
427n/a{
428n/a PyObject *callback;
429n/a PyObject *result;
430n/a
431n/a if (what == PyTrace_CALL)
432n/a callback = self;
433n/a else
434n/a callback = frame->f_trace;
435n/a if (callback == NULL)
436n/a return 0;
437n/a result = call_trampoline(callback, frame, what, arg);
438n/a if (result == NULL) {
439n/a PyEval_SetTrace(NULL, NULL);
440n/a Py_CLEAR(frame->f_trace);
441n/a return -1;
442n/a }
443n/a if (result != Py_None) {
444n/a Py_XSETREF(frame->f_trace, result);
445n/a }
446n/a else {
447n/a Py_DECREF(result);
448n/a }
449n/a return 0;
450n/a}
451n/a
452n/astatic PyObject *
453n/asys_settrace(PyObject *self, PyObject *args)
454n/a{
455n/a if (trace_init() == -1)
456n/a return NULL;
457n/a if (args == Py_None)
458n/a PyEval_SetTrace(NULL, NULL);
459n/a else
460n/a PyEval_SetTrace(trace_trampoline, args);
461n/a Py_RETURN_NONE;
462n/a}
463n/a
464n/aPyDoc_STRVAR(settrace_doc,
465n/a"settrace(function)\n\
466n/a\n\
467n/aSet the global debug tracing function. It will be called on each\n\
468n/afunction call. See the debugger chapter in the library manual."
469n/a);
470n/a
471n/astatic PyObject *
472n/asys_gettrace(PyObject *self, PyObject *args)
473n/a{
474n/a PyThreadState *tstate = PyThreadState_GET();
475n/a PyObject *temp = tstate->c_traceobj;
476n/a
477n/a if (temp == NULL)
478n/a temp = Py_None;
479n/a Py_INCREF(temp);
480n/a return temp;
481n/a}
482n/a
483n/aPyDoc_STRVAR(gettrace_doc,
484n/a"gettrace()\n\
485n/a\n\
486n/aReturn the global debug tracing function set with sys.settrace.\n\
487n/aSee the debugger chapter in the library manual."
488n/a);
489n/a
490n/astatic PyObject *
491n/asys_setprofile(PyObject *self, PyObject *args)
492n/a{
493n/a if (trace_init() == -1)
494n/a return NULL;
495n/a if (args == Py_None)
496n/a PyEval_SetProfile(NULL, NULL);
497n/a else
498n/a PyEval_SetProfile(profile_trampoline, args);
499n/a Py_RETURN_NONE;
500n/a}
501n/a
502n/aPyDoc_STRVAR(setprofile_doc,
503n/a"setprofile(function)\n\
504n/a\n\
505n/aSet the profiling function. It will be called on each function call\n\
506n/aand return. See the profiler chapter in the library manual."
507n/a);
508n/a
509n/astatic PyObject *
510n/asys_getprofile(PyObject *self, PyObject *args)
511n/a{
512n/a PyThreadState *tstate = PyThreadState_GET();
513n/a PyObject *temp = tstate->c_profileobj;
514n/a
515n/a if (temp == NULL)
516n/a temp = Py_None;
517n/a Py_INCREF(temp);
518n/a return temp;
519n/a}
520n/a
521n/aPyDoc_STRVAR(getprofile_doc,
522n/a"getprofile()\n\
523n/a\n\
524n/aReturn the profiling function set with sys.setprofile.\n\
525n/aSee the profiler chapter in the library manual."
526n/a);
527n/a
528n/astatic int _check_interval = 100;
529n/a
530n/astatic PyObject *
531n/asys_setcheckinterval(PyObject *self, PyObject *args)
532n/a{
533n/a if (PyErr_WarnEx(PyExc_DeprecationWarning,
534n/a "sys.getcheckinterval() and sys.setcheckinterval() "
535n/a "are deprecated. Use sys.setswitchinterval() "
536n/a "instead.", 1) < 0)
537n/a return NULL;
538n/a if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
539n/a return NULL;
540n/a Py_RETURN_NONE;
541n/a}
542n/a
543n/aPyDoc_STRVAR(setcheckinterval_doc,
544n/a"setcheckinterval(n)\n\
545n/a\n\
546n/aTell the Python interpreter to check for asynchronous events every\n\
547n/an instructions. This also affects how often thread switches occur."
548n/a);
549n/a
550n/astatic PyObject *
551n/asys_getcheckinterval(PyObject *self, PyObject *args)
552n/a{
553n/a if (PyErr_WarnEx(PyExc_DeprecationWarning,
554n/a "sys.getcheckinterval() and sys.setcheckinterval() "
555n/a "are deprecated. Use sys.getswitchinterval() "
556n/a "instead.", 1) < 0)
557n/a return NULL;
558n/a return PyLong_FromLong(_check_interval);
559n/a}
560n/a
561n/aPyDoc_STRVAR(getcheckinterval_doc,
562n/a"getcheckinterval() -> current check interval; see setcheckinterval()."
563n/a);
564n/a
565n/a#ifdef WITH_THREAD
566n/astatic PyObject *
567n/asys_setswitchinterval(PyObject *self, PyObject *args)
568n/a{
569n/a double d;
570n/a if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
571n/a return NULL;
572n/a if (d <= 0.0) {
573n/a PyErr_SetString(PyExc_ValueError,
574n/a "switch interval must be strictly positive");
575n/a return NULL;
576n/a }
577n/a _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
578n/a Py_RETURN_NONE;
579n/a}
580n/a
581n/aPyDoc_STRVAR(setswitchinterval_doc,
582n/a"setswitchinterval(n)\n\
583n/a\n\
584n/aSet the ideal thread switching delay inside the Python interpreter\n\
585n/aThe actual frequency of switching threads can be lower if the\n\
586n/ainterpreter executes long sequences of uninterruptible code\n\
587n/a(this is implementation-specific and workload-dependent).\n\
588n/a\n\
589n/aThe parameter must represent the desired switching delay in seconds\n\
590n/aA typical value is 0.005 (5 milliseconds)."
591n/a);
592n/a
593n/astatic PyObject *
594n/asys_getswitchinterval(PyObject *self, PyObject *args)
595n/a{
596n/a return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
597n/a}
598n/a
599n/aPyDoc_STRVAR(getswitchinterval_doc,
600n/a"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
601n/a);
602n/a
603n/a#endif /* WITH_THREAD */
604n/a
605n/astatic PyObject *
606n/asys_setrecursionlimit(PyObject *self, PyObject *args)
607n/a{
608n/a int new_limit, mark;
609n/a PyThreadState *tstate;
610n/a
611n/a if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
612n/a return NULL;
613n/a
614n/a if (new_limit < 1) {
615n/a PyErr_SetString(PyExc_ValueError,
616n/a "recursion limit must be greater or equal than 1");
617n/a return NULL;
618n/a }
619n/a
620n/a /* Issue #25274: When the recursion depth hits the recursion limit in
621n/a _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
622n/a set to 1 and a RecursionError is raised. The overflowed flag is reset
623n/a to 0 when the recursion depth goes below the low-water mark: see
624n/a Py_LeaveRecursiveCall().
625n/a
626n/a Reject too low new limit if the current recursion depth is higher than
627n/a the new low-water mark. Otherwise it may not be possible anymore to
628n/a reset the overflowed flag to 0. */
629n/a mark = _Py_RecursionLimitLowerWaterMark(new_limit);
630n/a tstate = PyThreadState_GET();
631n/a if (tstate->recursion_depth >= mark) {
632n/a PyErr_Format(PyExc_RecursionError,
633n/a "cannot set the recursion limit to %i at "
634n/a "the recursion depth %i: the limit is too low",
635n/a new_limit, tstate->recursion_depth);
636n/a return NULL;
637n/a }
638n/a
639n/a Py_SetRecursionLimit(new_limit);
640n/a Py_RETURN_NONE;
641n/a}
642n/a
643n/astatic PyObject *
644n/asys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
645n/a{
646n/a if (wrapper != Py_None) {
647n/a if (!PyCallable_Check(wrapper)) {
648n/a PyErr_Format(PyExc_TypeError,
649n/a "callable expected, got %.50s",
650n/a Py_TYPE(wrapper)->tp_name);
651n/a return NULL;
652n/a }
653n/a _PyEval_SetCoroutineWrapper(wrapper);
654n/a }
655n/a else {
656n/a _PyEval_SetCoroutineWrapper(NULL);
657n/a }
658n/a Py_RETURN_NONE;
659n/a}
660n/a
661n/aPyDoc_STRVAR(set_coroutine_wrapper_doc,
662n/a"set_coroutine_wrapper(wrapper)\n\
663n/a\n\
664n/aSet a wrapper for coroutine objects."
665n/a);
666n/a
667n/astatic PyObject *
668n/asys_get_coroutine_wrapper(PyObject *self, PyObject *args)
669n/a{
670n/a PyObject *wrapper = _PyEval_GetCoroutineWrapper();
671n/a if (wrapper == NULL) {
672n/a wrapper = Py_None;
673n/a }
674n/a Py_INCREF(wrapper);
675n/a return wrapper;
676n/a}
677n/a
678n/aPyDoc_STRVAR(get_coroutine_wrapper_doc,
679n/a"get_coroutine_wrapper()\n\
680n/a\n\
681n/aReturn the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
682n/a);
683n/a
684n/a
685n/astatic PyTypeObject AsyncGenHooksType;
686n/a
687n/aPyDoc_STRVAR(asyncgen_hooks_doc,
688n/a"asyncgen_hooks\n\
689n/a\n\
690n/aA struct sequence providing information about asynhronous\n\
691n/agenerators hooks. The attributes are read only.");
692n/a
693n/astatic PyStructSequence_Field asyncgen_hooks_fields[] = {
694n/a {"firstiter", "Hook to intercept first iteration"},
695n/a {"finalizer", "Hook to intercept finalization"},
696n/a {0}
697n/a};
698n/a
699n/astatic PyStructSequence_Desc asyncgen_hooks_desc = {
700n/a "asyncgen_hooks", /* name */
701n/a asyncgen_hooks_doc, /* doc */
702n/a asyncgen_hooks_fields , /* fields */
703n/a 2
704n/a};
705n/a
706n/a
707n/astatic PyObject *
708n/asys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
709n/a{
710n/a static char *keywords[] = {"firstiter", "finalizer", NULL};
711n/a PyObject *firstiter = NULL;
712n/a PyObject *finalizer = NULL;
713n/a
714n/a if (!PyArg_ParseTupleAndKeywords(
715n/a args, kw, "|OO", keywords,
716n/a &firstiter, &finalizer)) {
717n/a return NULL;
718n/a }
719n/a
720n/a if (finalizer && finalizer != Py_None) {
721n/a if (!PyCallable_Check(finalizer)) {
722n/a PyErr_Format(PyExc_TypeError,
723n/a "callable finalizer expected, got %.50s",
724n/a Py_TYPE(finalizer)->tp_name);
725n/a return NULL;
726n/a }
727n/a _PyEval_SetAsyncGenFinalizer(finalizer);
728n/a }
729n/a else if (finalizer == Py_None) {
730n/a _PyEval_SetAsyncGenFinalizer(NULL);
731n/a }
732n/a
733n/a if (firstiter && firstiter != Py_None) {
734n/a if (!PyCallable_Check(firstiter)) {
735n/a PyErr_Format(PyExc_TypeError,
736n/a "callable firstiter expected, got %.50s",
737n/a Py_TYPE(firstiter)->tp_name);
738n/a return NULL;
739n/a }
740n/a _PyEval_SetAsyncGenFirstiter(firstiter);
741n/a }
742n/a else if (firstiter == Py_None) {
743n/a _PyEval_SetAsyncGenFirstiter(NULL);
744n/a }
745n/a
746n/a Py_RETURN_NONE;
747n/a}
748n/a
749n/aPyDoc_STRVAR(set_asyncgen_hooks_doc,
750n/a"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
751n/a\n\
752n/aSet a finalizer for async generators objects."
753n/a);
754n/a
755n/astatic PyObject *
756n/asys_get_asyncgen_hooks(PyObject *self, PyObject *args)
757n/a{
758n/a PyObject *res;
759n/a PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
760n/a PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
761n/a
762n/a res = PyStructSequence_New(&AsyncGenHooksType);
763n/a if (res == NULL) {
764n/a return NULL;
765n/a }
766n/a
767n/a if (firstiter == NULL) {
768n/a firstiter = Py_None;
769n/a }
770n/a
771n/a if (finalizer == NULL) {
772n/a finalizer = Py_None;
773n/a }
774n/a
775n/a Py_INCREF(firstiter);
776n/a PyStructSequence_SET_ITEM(res, 0, firstiter);
777n/a
778n/a Py_INCREF(finalizer);
779n/a PyStructSequence_SET_ITEM(res, 1, finalizer);
780n/a
781n/a return res;
782n/a}
783n/a
784n/aPyDoc_STRVAR(get_asyncgen_hooks_doc,
785n/a"get_asyncgen_hooks()\n\
786n/a\n\
787n/aReturn a namedtuple of installed asynchronous generators hooks \
788n/a(firstiter, finalizer)."
789n/a);
790n/a
791n/a
792n/astatic PyTypeObject Hash_InfoType;
793n/a
794n/aPyDoc_STRVAR(hash_info_doc,
795n/a"hash_info\n\
796n/a\n\
797n/aA struct sequence providing parameters used for computing\n\
798n/ahashes. The attributes are read only.");
799n/a
800n/astatic PyStructSequence_Field hash_info_fields[] = {
801n/a {"width", "width of the type used for hashing, in bits"},
802n/a {"modulus", "prime number giving the modulus on which the hash "
803n/a "function is based"},
804n/a {"inf", "value to be used for hash of a positive infinity"},
805n/a {"nan", "value to be used for hash of a nan"},
806n/a {"imag", "multiplier used for the imaginary part of a complex number"},
807n/a {"algorithm", "name of the algorithm for hashing of str, bytes and "
808n/a "memoryviews"},
809n/a {"hash_bits", "internal output size of hash algorithm"},
810n/a {"seed_bits", "seed size of hash algorithm"},
811n/a {"cutoff", "small string optimization cutoff"},
812n/a {NULL, NULL}
813n/a};
814n/a
815n/astatic PyStructSequence_Desc hash_info_desc = {
816n/a "sys.hash_info",
817n/a hash_info_doc,
818n/a hash_info_fields,
819n/a 9,
820n/a};
821n/a
822n/astatic PyObject *
823n/aget_hash_info(void)
824n/a{
825n/a PyObject *hash_info;
826n/a int field = 0;
827n/a PyHash_FuncDef *hashfunc;
828n/a hash_info = PyStructSequence_New(&Hash_InfoType);
829n/a if (hash_info == NULL)
830n/a return NULL;
831n/a hashfunc = PyHash_GetFuncDef();
832n/a PyStructSequence_SET_ITEM(hash_info, field++,
833n/a PyLong_FromLong(8*sizeof(Py_hash_t)));
834n/a PyStructSequence_SET_ITEM(hash_info, field++,
835n/a PyLong_FromSsize_t(_PyHASH_MODULUS));
836n/a PyStructSequence_SET_ITEM(hash_info, field++,
837n/a PyLong_FromLong(_PyHASH_INF));
838n/a PyStructSequence_SET_ITEM(hash_info, field++,
839n/a PyLong_FromLong(_PyHASH_NAN));
840n/a PyStructSequence_SET_ITEM(hash_info, field++,
841n/a PyLong_FromLong(_PyHASH_IMAG));
842n/a PyStructSequence_SET_ITEM(hash_info, field++,
843n/a PyUnicode_FromString(hashfunc->name));
844n/a PyStructSequence_SET_ITEM(hash_info, field++,
845n/a PyLong_FromLong(hashfunc->hash_bits));
846n/a PyStructSequence_SET_ITEM(hash_info, field++,
847n/a PyLong_FromLong(hashfunc->seed_bits));
848n/a PyStructSequence_SET_ITEM(hash_info, field++,
849n/a PyLong_FromLong(Py_HASH_CUTOFF));
850n/a if (PyErr_Occurred()) {
851n/a Py_CLEAR(hash_info);
852n/a return NULL;
853n/a }
854n/a return hash_info;
855n/a}
856n/a
857n/a
858n/aPyDoc_STRVAR(setrecursionlimit_doc,
859n/a"setrecursionlimit(n)\n\
860n/a\n\
861n/aSet the maximum depth of the Python interpreter stack to n. This\n\
862n/alimit prevents infinite recursion from causing an overflow of the C\n\
863n/astack and crashing Python. The highest possible limit is platform-\n\
864n/adependent."
865n/a);
866n/a
867n/astatic PyObject *
868n/asys_getrecursionlimit(PyObject *self)
869n/a{
870n/a return PyLong_FromLong(Py_GetRecursionLimit());
871n/a}
872n/a
873n/aPyDoc_STRVAR(getrecursionlimit_doc,
874n/a"getrecursionlimit()\n\
875n/a\n\
876n/aReturn the current value of the recursion limit, the maximum depth\n\
877n/aof the Python interpreter stack. This limit prevents infinite\n\
878n/arecursion from causing an overflow of the C stack and crashing Python."
879n/a);
880n/a
881n/a#ifdef MS_WINDOWS
882n/aPyDoc_STRVAR(getwindowsversion_doc,
883n/a"getwindowsversion()\n\
884n/a\n\
885n/aReturn information about the running version of Windows as a named tuple.\n\
886n/aThe members are named: major, minor, build, platform, service_pack,\n\
887n/aservice_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
888n/abackward compatibility, only the first 5 items are available by indexing.\n\
889n/aAll elements are numbers, except service_pack and platform_type which are\n\
890n/astrings, and platform_version which is a 3-tuple. Platform is always 2.\n\
891n/aProduct_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
892n/aserver. Platform_version is a 3-tuple containing a version number that is\n\
893n/aintended for identifying the OS rather than feature detection."
894n/a);
895n/a
896n/astatic PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
897n/a
898n/astatic PyStructSequence_Field windows_version_fields[] = {
899n/a {"major", "Major version number"},
900n/a {"minor", "Minor version number"},
901n/a {"build", "Build number"},
902n/a {"platform", "Operating system platform"},
903n/a {"service_pack", "Latest Service Pack installed on the system"},
904n/a {"service_pack_major", "Service Pack major version number"},
905n/a {"service_pack_minor", "Service Pack minor version number"},
906n/a {"suite_mask", "Bit mask identifying available product suites"},
907n/a {"product_type", "System product type"},
908n/a {"platform_version", "Diagnostic version number"},
909n/a {0}
910n/a};
911n/a
912n/astatic PyStructSequence_Desc windows_version_desc = {
913n/a "sys.getwindowsversion", /* name */
914n/a getwindowsversion_doc, /* doc */
915n/a windows_version_fields, /* fields */
916n/a 5 /* For backward compatibility,
917n/a only the first 5 items are accessible
918n/a via indexing, the rest are name only */
919n/a};
920n/a
921n/a/* Disable deprecation warnings about GetVersionEx as the result is
922n/a being passed straight through to the caller, who is responsible for
923n/a using it correctly. */
924n/a#pragma warning(push)
925n/a#pragma warning(disable:4996)
926n/a
927n/astatic PyObject *
928n/asys_getwindowsversion(PyObject *self)
929n/a{
930n/a PyObject *version;
931n/a int pos = 0;
932n/a OSVERSIONINFOEX ver;
933n/a DWORD realMajor, realMinor, realBuild;
934n/a HANDLE hKernel32;
935n/a wchar_t kernel32_path[MAX_PATH];
936n/a LPVOID verblock;
937n/a DWORD verblock_size;
938n/a
939n/a ver.dwOSVersionInfoSize = sizeof(ver);
940n/a if (!GetVersionEx((OSVERSIONINFO*) &ver))
941n/a return PyErr_SetFromWindowsErr(0);
942n/a
943n/a version = PyStructSequence_New(&WindowsVersionType);
944n/a if (version == NULL)
945n/a return NULL;
946n/a
947n/a PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
948n/a PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
949n/a PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
950n/a PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
951n/a PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
952n/a PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
953n/a PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
954n/a PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
955n/a PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
956n/a
957n/a realMajor = ver.dwMajorVersion;
958n/a realMinor = ver.dwMinorVersion;
959n/a realBuild = ver.dwBuildNumber;
960n/a
961n/a // GetVersion will lie if we are running in a compatibility mode.
962n/a // We need to read the version info from a system file resource
963n/a // to accurately identify the OS version. If we fail for any reason,
964n/a // just return whatever GetVersion said.
965n/a hKernel32 = GetModuleHandleW(L"kernel32.dll");
966n/a if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
967n/a (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
968n/a (verblock = PyMem_RawMalloc(verblock_size))) {
969n/a VS_FIXEDFILEINFO *ffi;
970n/a UINT ffi_len;
971n/a
972n/a if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
973n/a VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
974n/a realMajor = HIWORD(ffi->dwProductVersionMS);
975n/a realMinor = LOWORD(ffi->dwProductVersionMS);
976n/a realBuild = HIWORD(ffi->dwProductVersionLS);
977n/a }
978n/a PyMem_RawFree(verblock);
979n/a }
980n/a PyStructSequence_SET_ITEM(version, pos++, PyTuple_Pack(3,
981n/a PyLong_FromLong(realMajor),
982n/a PyLong_FromLong(realMinor),
983n/a PyLong_FromLong(realBuild)
984n/a ));
985n/a
986n/a if (PyErr_Occurred()) {
987n/a Py_DECREF(version);
988n/a return NULL;
989n/a }
990n/a
991n/a return version;
992n/a}
993n/a
994n/a#pragma warning(pop)
995n/a
996n/aPyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
997n/a"_enablelegacywindowsfsencoding()\n\
998n/a\n\
999n/aChanges the default filesystem encoding to mbcs:replace for consistency\n\
1000n/awith earlier versions of Python. See PEP 529 for more information.\n\
1001n/a\n\
1002n/aThis is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
1003n/aenvironment variable before launching Python."
1004n/a);
1005n/a
1006n/astatic PyObject *
1007n/asys_enablelegacywindowsfsencoding(PyObject *self)
1008n/a{
1009n/a Py_FileSystemDefaultEncoding = "mbcs";
1010n/a Py_FileSystemDefaultEncodeErrors = "replace";
1011n/a Py_RETURN_NONE;
1012n/a}
1013n/a
1014n/a#endif /* MS_WINDOWS */
1015n/a
1016n/a#ifdef HAVE_DLOPEN
1017n/astatic PyObject *
1018n/asys_setdlopenflags(PyObject *self, PyObject *args)
1019n/a{
1020n/a int new_val;
1021n/a PyThreadState *tstate = PyThreadState_GET();
1022n/a if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1023n/a return NULL;
1024n/a if (!tstate)
1025n/a return NULL;
1026n/a tstate->interp->dlopenflags = new_val;
1027n/a Py_RETURN_NONE;
1028n/a}
1029n/a
1030n/aPyDoc_STRVAR(setdlopenflags_doc,
1031n/a"setdlopenflags(n) -> None\n\
1032n/a\n\
1033n/aSet the flags used by the interpreter for dlopen calls, such as when the\n\
1034n/ainterpreter loads extension modules. Among other things, this will enable\n\
1035n/aa lazy resolving of symbols when importing a module, if called as\n\
1036n/asys.setdlopenflags(0). To share symbols across extension modules, call as\n\
1037n/asys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
1038n/acan be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
1039n/a
1040n/astatic PyObject *
1041n/asys_getdlopenflags(PyObject *self, PyObject *args)
1042n/a{
1043n/a PyThreadState *tstate = PyThreadState_GET();
1044n/a if (!tstate)
1045n/a return NULL;
1046n/a return PyLong_FromLong(tstate->interp->dlopenflags);
1047n/a}
1048n/a
1049n/aPyDoc_STRVAR(getdlopenflags_doc,
1050n/a"getdlopenflags() -> int\n\
1051n/a\n\
1052n/aReturn the current value of the flags that are used for dlopen calls.\n\
1053n/aThe flag constants are defined in the os module.");
1054n/a
1055n/a#endif /* HAVE_DLOPEN */
1056n/a
1057n/a#ifdef USE_MALLOPT
1058n/a/* Link with -lmalloc (or -lmpc) on an SGI */
1059n/a#include <malloc.h>
1060n/a
1061n/astatic PyObject *
1062n/asys_mdebug(PyObject *self, PyObject *args)
1063n/a{
1064n/a int flag;
1065n/a if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1066n/a return NULL;
1067n/a mallopt(M_DEBUG, flag);
1068n/a Py_RETURN_NONE;
1069n/a}
1070n/a#endif /* USE_MALLOPT */
1071n/a
1072n/asize_t
1073n/a_PySys_GetSizeOf(PyObject *o)
1074n/a{
1075n/a PyObject *res = NULL;
1076n/a PyObject *method;
1077n/a Py_ssize_t size;
1078n/a
1079n/a /* Make sure the type is initialized. float gets initialized late */
1080n/a if (PyType_Ready(Py_TYPE(o)) < 0)
1081n/a return (size_t)-1;
1082n/a
1083n/a method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
1084n/a if (method == NULL) {
1085n/a if (!PyErr_Occurred())
1086n/a PyErr_Format(PyExc_TypeError,
1087n/a "Type %.100s doesn't define __sizeof__",
1088n/a Py_TYPE(o)->tp_name);
1089n/a }
1090n/a else {
1091n/a res = _PyObject_CallNoArg(method);
1092n/a Py_DECREF(method);
1093n/a }
1094n/a
1095n/a if (res == NULL)
1096n/a return (size_t)-1;
1097n/a
1098n/a size = PyLong_AsSsize_t(res);
1099n/a Py_DECREF(res);
1100n/a if (size == -1 && PyErr_Occurred())
1101n/a return (size_t)-1;
1102n/a
1103n/a if (size < 0) {
1104n/a PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1105n/a return (size_t)-1;
1106n/a }
1107n/a
1108n/a /* add gc_head size */
1109n/a if (PyObject_IS_GC(o))
1110n/a return ((size_t)size) + sizeof(PyGC_Head);
1111n/a return (size_t)size;
1112n/a}
1113n/a
1114n/astatic PyObject *
1115n/asys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1116n/a{
1117n/a static char *kwlist[] = {"object", "default", 0};
1118n/a size_t size;
1119n/a PyObject *o, *dflt = NULL;
1120n/a
1121n/a if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1122n/a kwlist, &o, &dflt))
1123n/a return NULL;
1124n/a
1125n/a size = _PySys_GetSizeOf(o);
1126n/a
1127n/a if (size == (size_t)-1 && PyErr_Occurred()) {
1128n/a /* Has a default value been given */
1129n/a if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1130n/a PyErr_Clear();
1131n/a Py_INCREF(dflt);
1132n/a return dflt;
1133n/a }
1134n/a else
1135n/a return NULL;
1136n/a }
1137n/a
1138n/a return PyLong_FromSize_t(size);
1139n/a}
1140n/a
1141n/aPyDoc_STRVAR(getsizeof_doc,
1142n/a"getsizeof(object, default) -> int\n\
1143n/a\n\
1144n/aReturn the size of object in bytes.");
1145n/a
1146n/astatic PyObject *
1147n/asys_getrefcount(PyObject *self, PyObject *arg)
1148n/a{
1149n/a return PyLong_FromSsize_t(arg->ob_refcnt);
1150n/a}
1151n/a
1152n/a#ifdef Py_REF_DEBUG
1153n/astatic PyObject *
1154n/asys_gettotalrefcount(PyObject *self)
1155n/a{
1156n/a return PyLong_FromSsize_t(_Py_GetRefTotal());
1157n/a}
1158n/a#endif /* Py_REF_DEBUG */
1159n/a
1160n/aPyDoc_STRVAR(getrefcount_doc,
1161n/a"getrefcount(object) -> integer\n\
1162n/a\n\
1163n/aReturn the reference count of object. The count returned is generally\n\
1164n/aone higher than you might expect, because it includes the (temporary)\n\
1165n/areference as an argument to getrefcount()."
1166n/a);
1167n/a
1168n/astatic PyObject *
1169n/asys_getallocatedblocks(PyObject *self)
1170n/a{
1171n/a return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1172n/a}
1173n/a
1174n/aPyDoc_STRVAR(getallocatedblocks_doc,
1175n/a"getallocatedblocks() -> integer\n\
1176n/a\n\
1177n/aReturn the number of memory blocks currently allocated, regardless of their\n\
1178n/asize."
1179n/a);
1180n/a
1181n/a#ifdef COUNT_ALLOCS
1182n/astatic PyObject *
1183n/asys_getcounts(PyObject *self)
1184n/a{
1185n/a extern PyObject *get_counts(void);
1186n/a
1187n/a return get_counts();
1188n/a}
1189n/a#endif
1190n/a
1191n/aPyDoc_STRVAR(getframe_doc,
1192n/a"_getframe([depth]) -> frameobject\n\
1193n/a\n\
1194n/aReturn a frame object from the call stack. If optional integer depth is\n\
1195n/agiven, return the frame object that many calls below the top of the stack.\n\
1196n/aIf that is deeper than the call stack, ValueError is raised. The default\n\
1197n/afor depth is zero, returning the frame at the top of the call stack.\n\
1198n/a\n\
1199n/aThis function should be used for internal and specialized\n\
1200n/apurposes only."
1201n/a);
1202n/a
1203n/astatic PyObject *
1204n/asys_getframe(PyObject *self, PyObject *args)
1205n/a{
1206n/a PyFrameObject *f = PyThreadState_GET()->frame;
1207n/a int depth = -1;
1208n/a
1209n/a if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1210n/a return NULL;
1211n/a
1212n/a while (depth > 0 && f != NULL) {
1213n/a f = f->f_back;
1214n/a --depth;
1215n/a }
1216n/a if (f == NULL) {
1217n/a PyErr_SetString(PyExc_ValueError,
1218n/a "call stack is not deep enough");
1219n/a return NULL;
1220n/a }
1221n/a Py_INCREF(f);
1222n/a return (PyObject*)f;
1223n/a}
1224n/a
1225n/aPyDoc_STRVAR(current_frames_doc,
1226n/a"_current_frames() -> dictionary\n\
1227n/a\n\
1228n/aReturn a dictionary mapping each current thread T's thread id to T's\n\
1229n/acurrent stack frame.\n\
1230n/a\n\
1231n/aThis function should be used for specialized purposes only."
1232n/a);
1233n/a
1234n/astatic PyObject *
1235n/asys_current_frames(PyObject *self, PyObject *noargs)
1236n/a{
1237n/a return _PyThread_CurrentFrames();
1238n/a}
1239n/a
1240n/aPyDoc_STRVAR(call_tracing_doc,
1241n/a"call_tracing(func, args) -> object\n\
1242n/a\n\
1243n/aCall func(*args), while tracing is enabled. The tracing state is\n\
1244n/asaved, and restored afterwards. This is intended to be called from\n\
1245n/aa debugger from a checkpoint, to recursively debug some other code."
1246n/a);
1247n/a
1248n/astatic PyObject *
1249n/asys_call_tracing(PyObject *self, PyObject *args)
1250n/a{
1251n/a PyObject *func, *funcargs;
1252n/a if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1253n/a return NULL;
1254n/a return _PyEval_CallTracing(func, funcargs);
1255n/a}
1256n/a
1257n/aPyDoc_STRVAR(callstats_doc,
1258n/a"callstats() -> tuple of integers\n\
1259n/a\n\
1260n/aReturn a tuple of function call statistics, if CALL_PROFILE was defined\n\
1261n/awhen Python was built. Otherwise, return None.\n\
1262n/a\n\
1263n/aWhen enabled, this function returns detailed, implementation-specific\n\
1264n/adetails about the number of function calls executed. The return value is\n\
1265n/aa 11-tuple where the entries in the tuple are counts of:\n\
1266n/a0. all function calls\n\
1267n/a1. calls to PyFunction_Type objects\n\
1268n/a2. PyFunction calls that do not create an argument tuple\n\
1269n/a3. PyFunction calls that do not create an argument tuple\n\
1270n/a and bypass PyEval_EvalCodeEx()\n\
1271n/a4. PyMethod calls\n\
1272n/a5. PyMethod calls on bound methods\n\
1273n/a6. PyType calls\n\
1274n/a7. PyCFunction calls\n\
1275n/a8. generator calls\n\
1276n/a9. All other calls\n\
1277n/a10. Number of stack pops performed by call_function()"
1278n/a);
1279n/a
1280n/astatic PyObject *
1281n/asys_callstats(PyObject *self)
1282n/a{
1283n/a if (PyErr_WarnEx(PyExc_DeprecationWarning,
1284n/a "sys.callstats() has been deprecated in Python 3.7 "
1285n/a "and will be removed in the future", 1) < 0) {
1286n/a return NULL;
1287n/a }
1288n/a
1289n/a Py_RETURN_NONE;
1290n/a}
1291n/a
1292n/a
1293n/a#ifdef __cplusplus
1294n/aextern "C" {
1295n/a#endif
1296n/a
1297n/astatic PyObject *
1298n/asys_debugmallocstats(PyObject *self, PyObject *args)
1299n/a{
1300n/a#ifdef WITH_PYMALLOC
1301n/a if (_PyMem_PymallocEnabled()) {
1302n/a _PyObject_DebugMallocStats(stderr);
1303n/a fputc('\n', stderr);
1304n/a }
1305n/a#endif
1306n/a _PyObject_DebugTypeStats(stderr);
1307n/a
1308n/a Py_RETURN_NONE;
1309n/a}
1310n/aPyDoc_STRVAR(debugmallocstats_doc,
1311n/a"_debugmallocstats()\n\
1312n/a\n\
1313n/aPrint summary info to stderr about the state of\n\
1314n/apymalloc's structures.\n\
1315n/a\n\
1316n/aIn Py_DEBUG mode, also perform some expensive internal consistency\n\
1317n/achecks.\n\
1318n/a");
1319n/a
1320n/a#ifdef Py_TRACE_REFS
1321n/a/* Defined in objects.c because it uses static globals if that file */
1322n/aextern PyObject *_Py_GetObjects(PyObject *, PyObject *);
1323n/a#endif
1324n/a
1325n/a#ifdef DYNAMIC_EXECUTION_PROFILE
1326n/a/* Defined in ceval.c because it uses static globals if that file */
1327n/aextern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
1328n/a#endif
1329n/a
1330n/a#ifdef __cplusplus
1331n/a}
1332n/a#endif
1333n/a
1334n/astatic PyObject *
1335n/asys_clear_type_cache(PyObject* self, PyObject* args)
1336n/a{
1337n/a PyType_ClearCache();
1338n/a Py_RETURN_NONE;
1339n/a}
1340n/a
1341n/aPyDoc_STRVAR(sys_clear_type_cache__doc__,
1342n/a"_clear_type_cache() -> None\n\
1343n/aClear the internal type lookup cache.");
1344n/a
1345n/astatic PyObject *
1346n/asys_is_finalizing(PyObject* self, PyObject* args)
1347n/a{
1348n/a return PyBool_FromLong(_Py_Finalizing != NULL);
1349n/a}
1350n/a
1351n/aPyDoc_STRVAR(is_finalizing_doc,
1352n/a"is_finalizing()\n\
1353n/aReturn True if Python is exiting.");
1354n/a
1355n/a
1356n/a#ifdef ANDROID_API_LEVEL
1357n/aPyDoc_STRVAR(getandroidapilevel_doc,
1358n/a"getandroidapilevel()\n\
1359n/a\n\
1360n/aReturn the build time API version of Android as an integer.");
1361n/a
1362n/astatic PyObject *
1363n/asys_getandroidapilevel(PyObject *self)
1364n/a{
1365n/a return PyLong_FromLong(ANDROID_API_LEVEL);
1366n/a}
1367n/a#endif /* ANDROID_API_LEVEL */
1368n/a
1369n/a
1370n/astatic PyMethodDef sys_methods[] = {
1371n/a /* Might as well keep this in alphabetic order */
1372n/a {"callstats", (PyCFunction)sys_callstats, METH_NOARGS,
1373n/a callstats_doc},
1374n/a {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1375n/a sys_clear_type_cache__doc__},
1376n/a {"_current_frames", sys_current_frames, METH_NOARGS,
1377n/a current_frames_doc},
1378n/a {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1379n/a {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1380n/a {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1381n/a {"exit", sys_exit, METH_VARARGS, exit_doc},
1382n/a {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1383n/a METH_NOARGS, getdefaultencoding_doc},
1384n/a#ifdef HAVE_DLOPEN
1385n/a {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1386n/a getdlopenflags_doc},
1387n/a#endif
1388n/a {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1389n/a getallocatedblocks_doc},
1390n/a#ifdef COUNT_ALLOCS
1391n/a {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
1392n/a#endif
1393n/a#ifdef DYNAMIC_EXECUTION_PROFILE
1394n/a {"getdxp", _Py_GetDXProfile, METH_VARARGS},
1395n/a#endif
1396n/a {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1397n/a METH_NOARGS, getfilesystemencoding_doc},
1398n/a { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1399n/a METH_NOARGS, getfilesystemencodeerrors_doc },
1400n/a#ifdef Py_TRACE_REFS
1401n/a {"getobjects", _Py_GetObjects, METH_VARARGS},
1402n/a#endif
1403n/a#ifdef Py_REF_DEBUG
1404n/a {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
1405n/a#endif
1406n/a {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1407n/a {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1408n/a getrecursionlimit_doc},
1409n/a {"getsizeof", (PyCFunction)sys_getsizeof,
1410n/a METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1411n/a {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
1412n/a#ifdef MS_WINDOWS
1413n/a {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1414n/a getwindowsversion_doc},
1415n/a {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1416n/a METH_NOARGS, enablelegacywindowsfsencoding_doc },
1417n/a#endif /* MS_WINDOWS */
1418n/a {"intern", sys_intern, METH_VARARGS, intern_doc},
1419n/a {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
1420n/a#ifdef USE_MALLOPT
1421n/a {"mdebug", sys_mdebug, METH_VARARGS},
1422n/a#endif
1423n/a {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1424n/a setcheckinterval_doc},
1425n/a {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1426n/a getcheckinterval_doc},
1427n/a#ifdef WITH_THREAD
1428n/a {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1429n/a setswitchinterval_doc},
1430n/a {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1431n/a getswitchinterval_doc},
1432n/a#endif
1433n/a#ifdef HAVE_DLOPEN
1434n/a {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1435n/a setdlopenflags_doc},
1436n/a#endif
1437n/a {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1438n/a {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1439n/a {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1440n/a setrecursionlimit_doc},
1441n/a {"settrace", sys_settrace, METH_O, settrace_doc},
1442n/a {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1443n/a {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
1444n/a {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
1445n/a debugmallocstats_doc},
1446n/a {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1447n/a set_coroutine_wrapper_doc},
1448n/a {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1449n/a get_coroutine_wrapper_doc},
1450n/a {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
1451n/a METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1452n/a {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1453n/a get_asyncgen_hooks_doc},
1454n/a#ifdef ANDROID_API_LEVEL
1455n/a {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1456n/a getandroidapilevel_doc},
1457n/a#endif
1458n/a {NULL, NULL} /* sentinel */
1459n/a};
1460n/a
1461n/astatic PyObject *
1462n/alist_builtin_module_names(void)
1463n/a{
1464n/a PyObject *list = PyList_New(0);
1465n/a int i;
1466n/a if (list == NULL)
1467n/a return NULL;
1468n/a for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1469n/a PyObject *name = PyUnicode_FromString(
1470n/a PyImport_Inittab[i].name);
1471n/a if (name == NULL)
1472n/a break;
1473n/a PyList_Append(list, name);
1474n/a Py_DECREF(name);
1475n/a }
1476n/a if (PyList_Sort(list) != 0) {
1477n/a Py_DECREF(list);
1478n/a list = NULL;
1479n/a }
1480n/a if (list) {
1481n/a PyObject *v = PyList_AsTuple(list);
1482n/a Py_DECREF(list);
1483n/a list = v;
1484n/a }
1485n/a return list;
1486n/a}
1487n/a
1488n/astatic PyObject *warnoptions = NULL;
1489n/a
1490n/avoid
1491n/aPySys_ResetWarnOptions(void)
1492n/a{
1493n/a if (warnoptions == NULL || !PyList_Check(warnoptions))
1494n/a return;
1495n/a PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
1496n/a}
1497n/a
1498n/avoid
1499n/aPySys_AddWarnOptionUnicode(PyObject *unicode)
1500n/a{
1501n/a if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1502n/a Py_XDECREF(warnoptions);
1503n/a warnoptions = PyList_New(0);
1504n/a if (warnoptions == NULL)
1505n/a return;
1506n/a }
1507n/a PyList_Append(warnoptions, unicode);
1508n/a}
1509n/a
1510n/avoid
1511n/aPySys_AddWarnOption(const wchar_t *s)
1512n/a{
1513n/a PyObject *unicode;
1514n/a unicode = PyUnicode_FromWideChar(s, -1);
1515n/a if (unicode == NULL)
1516n/a return;
1517n/a PySys_AddWarnOptionUnicode(unicode);
1518n/a Py_DECREF(unicode);
1519n/a}
1520n/a
1521n/aint
1522n/aPySys_HasWarnOptions(void)
1523n/a{
1524n/a return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1525n/a}
1526n/a
1527n/astatic PyObject *xoptions = NULL;
1528n/a
1529n/astatic PyObject *
1530n/aget_xoptions(void)
1531n/a{
1532n/a if (xoptions == NULL || !PyDict_Check(xoptions)) {
1533n/a Py_XDECREF(xoptions);
1534n/a xoptions = PyDict_New();
1535n/a }
1536n/a return xoptions;
1537n/a}
1538n/a
1539n/avoid
1540n/aPySys_AddXOption(const wchar_t *s)
1541n/a{
1542n/a PyObject *opts;
1543n/a PyObject *name = NULL, *value = NULL;
1544n/a const wchar_t *name_end;
1545n/a
1546n/a opts = get_xoptions();
1547n/a if (opts == NULL)
1548n/a goto error;
1549n/a
1550n/a name_end = wcschr(s, L'=');
1551n/a if (!name_end) {
1552n/a name = PyUnicode_FromWideChar(s, -1);
1553n/a value = Py_True;
1554n/a Py_INCREF(value);
1555n/a }
1556n/a else {
1557n/a name = PyUnicode_FromWideChar(s, name_end - s);
1558n/a value = PyUnicode_FromWideChar(name_end + 1, -1);
1559n/a }
1560n/a if (name == NULL || value == NULL)
1561n/a goto error;
1562n/a PyDict_SetItem(opts, name, value);
1563n/a Py_DECREF(name);
1564n/a Py_DECREF(value);
1565n/a return;
1566n/a
1567n/aerror:
1568n/a Py_XDECREF(name);
1569n/a Py_XDECREF(value);
1570n/a /* No return value, therefore clear error state if possible */
1571n/a if (_PyThreadState_UncheckedGet()) {
1572n/a PyErr_Clear();
1573n/a }
1574n/a}
1575n/a
1576n/aPyObject *
1577n/aPySys_GetXOptions(void)
1578n/a{
1579n/a return get_xoptions();
1580n/a}
1581n/a
1582n/a/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1583n/a Two literals concatenated works just fine. If you have a K&R compiler
1584n/a or other abomination that however *does* understand longer strings,
1585n/a get rid of the !!! comment in the middle and the quotes that surround it. */
1586n/aPyDoc_VAR(sys_doc) =
1587n/aPyDoc_STR(
1588n/a"This module provides access to some objects used or maintained by the\n\
1589n/ainterpreter and to functions that interact strongly with the interpreter.\n\
1590n/a\n\
1591n/aDynamic objects:\n\
1592n/a\n\
1593n/aargv -- command line arguments; argv[0] is the script pathname if known\n\
1594n/apath -- module search path; path[0] is the script directory, else ''\n\
1595n/amodules -- dictionary of loaded modules\n\
1596n/a\n\
1597n/adisplayhook -- called to show results in an interactive session\n\
1598n/aexcepthook -- called to handle any uncaught exception other than SystemExit\n\
1599n/a To customize printing in an interactive session or to install a custom\n\
1600n/a top-level exception handler, assign other functions to replace these.\n\
1601n/a\n\
1602n/astdin -- standard input file object; used by input()\n\
1603n/astdout -- standard output file object; used by print()\n\
1604n/astderr -- standard error object; used for error messages\n\
1605n/a By assigning other file objects (or objects that behave like files)\n\
1606n/a to these, it is possible to redirect all of the interpreter's I/O.\n\
1607n/a\n\
1608n/alast_type -- type of last uncaught exception\n\
1609n/alast_value -- value of last uncaught exception\n\
1610n/alast_traceback -- traceback of last uncaught exception\n\
1611n/a These three are only available in an interactive session after a\n\
1612n/a traceback has been printed.\n\
1613n/a"
1614n/a)
1615n/a/* concatenating string here */
1616n/aPyDoc_STR(
1617n/a"\n\
1618n/aStatic objects:\n\
1619n/a\n\
1620n/abuiltin_module_names -- tuple of module names built into this interpreter\n\
1621n/acopyright -- copyright notice pertaining to this interpreter\n\
1622n/aexec_prefix -- prefix used to find the machine-specific Python library\n\
1623n/aexecutable -- absolute path of the executable binary of the Python interpreter\n\
1624n/afloat_info -- a struct sequence with information about the float implementation.\n\
1625n/afloat_repr_style -- string indicating the style of repr() output for floats\n\
1626n/ahash_info -- a struct sequence with information about the hash algorithm.\n\
1627n/ahexversion -- version information encoded as a single integer\n\
1628n/aimplementation -- Python implementation information.\n\
1629n/aint_info -- a struct sequence with information about the int implementation.\n\
1630n/amaxsize -- the largest supported length of containers.\n\
1631n/amaxunicode -- the value of the largest Unicode code point\n\
1632n/aplatform -- platform identifier\n\
1633n/aprefix -- prefix used to find the Python library\n\
1634n/athread_info -- a struct sequence with information about the thread implementation.\n\
1635n/aversion -- the version of this interpreter as a string\n\
1636n/aversion_info -- version information as a named tuple\n\
1637n/a"
1638n/a)
1639n/a#ifdef MS_COREDLL
1640n/a/* concatenating string here */
1641n/aPyDoc_STR(
1642n/a"dllhandle -- [Windows only] integer handle of the Python DLL\n\
1643n/awinver -- [Windows only] version number of the Python DLL\n\
1644n/a"
1645n/a)
1646n/a#endif /* MS_COREDLL */
1647n/a#ifdef MS_WINDOWS
1648n/a/* concatenating string here */
1649n/aPyDoc_STR(
1650n/a"_enablelegacywindowsfsencoding -- [Windows only] \n\
1651n/a"
1652n/a)
1653n/a#endif
1654n/aPyDoc_STR(
1655n/a"__stdin__ -- the original stdin; don't touch!\n\
1656n/a__stdout__ -- the original stdout; don't touch!\n\
1657n/a__stderr__ -- the original stderr; don't touch!\n\
1658n/a__displayhook__ -- the original displayhook; don't touch!\n\
1659n/a__excepthook__ -- the original excepthook; don't touch!\n\
1660n/a\n\
1661n/aFunctions:\n\
1662n/a\n\
1663n/adisplayhook() -- print an object to the screen, and save it in builtins._\n\
1664n/aexcepthook() -- print an exception and its traceback to sys.stderr\n\
1665n/aexc_info() -- return thread-safe information about the current exception\n\
1666n/aexit() -- exit the interpreter by raising SystemExit\n\
1667n/agetdlopenflags() -- returns flags to be used for dlopen() calls\n\
1668n/agetprofile() -- get the global profiling function\n\
1669n/agetrefcount() -- return the reference count for an object (plus one :-)\n\
1670n/agetrecursionlimit() -- return the max recursion depth for the interpreter\n\
1671n/agetsizeof() -- return the size of an object in bytes\n\
1672n/agettrace() -- get the global debug tracing function\n\
1673n/asetcheckinterval() -- control how often the interpreter checks for events\n\
1674n/asetdlopenflags() -- set the flags to be used for dlopen() calls\n\
1675n/asetprofile() -- set the global profiling function\n\
1676n/asetrecursionlimit() -- set the max recursion depth for the interpreter\n\
1677n/asettrace() -- set the global debug tracing function\n\
1678n/a"
1679n/a)
1680n/a/* end of sys_doc */ ;
1681n/a
1682n/a
1683n/aPyDoc_STRVAR(flags__doc__,
1684n/a"sys.flags\n\
1685n/a\n\
1686n/aFlags provided through command line arguments or environment vars.");
1687n/a
1688n/astatic PyTypeObject FlagsType;
1689n/a
1690n/astatic PyStructSequence_Field flags_fields[] = {
1691n/a {"debug", "-d"},
1692n/a {"inspect", "-i"},
1693n/a {"interactive", "-i"},
1694n/a {"optimize", "-O or -OO"},
1695n/a {"dont_write_bytecode", "-B"},
1696n/a {"no_user_site", "-s"},
1697n/a {"no_site", "-S"},
1698n/a {"ignore_environment", "-E"},
1699n/a {"verbose", "-v"},
1700n/a /* {"unbuffered", "-u"}, */
1701n/a /* {"skip_first", "-x"}, */
1702n/a {"bytes_warning", "-b"},
1703n/a {"quiet", "-q"},
1704n/a {"hash_randomization", "-R"},
1705n/a {"isolated", "-I"},
1706n/a {0}
1707n/a};
1708n/a
1709n/astatic PyStructSequence_Desc flags_desc = {
1710n/a "sys.flags", /* name */
1711n/a flags__doc__, /* doc */
1712n/a flags_fields, /* fields */
1713n/a 13
1714n/a};
1715n/a
1716n/astatic PyObject*
1717n/amake_flags(void)
1718n/a{
1719n/a int pos = 0;
1720n/a PyObject *seq;
1721n/a
1722n/a seq = PyStructSequence_New(&FlagsType);
1723n/a if (seq == NULL)
1724n/a return NULL;
1725n/a
1726n/a#define SetFlag(flag) \
1727n/a PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
1728n/a
1729n/a SetFlag(Py_DebugFlag);
1730n/a SetFlag(Py_InspectFlag);
1731n/a SetFlag(Py_InteractiveFlag);
1732n/a SetFlag(Py_OptimizeFlag);
1733n/a SetFlag(Py_DontWriteBytecodeFlag);
1734n/a SetFlag(Py_NoUserSiteDirectory);
1735n/a SetFlag(Py_NoSiteFlag);
1736n/a SetFlag(Py_IgnoreEnvironmentFlag);
1737n/a SetFlag(Py_VerboseFlag);
1738n/a /* SetFlag(saw_unbuffered_flag); */
1739n/a /* SetFlag(skipfirstline); */
1740n/a SetFlag(Py_BytesWarningFlag);
1741n/a SetFlag(Py_QuietFlag);
1742n/a SetFlag(Py_HashRandomizationFlag);
1743n/a SetFlag(Py_IsolatedFlag);
1744n/a#undef SetFlag
1745n/a
1746n/a if (PyErr_Occurred()) {
1747n/a Py_DECREF(seq);
1748n/a return NULL;
1749n/a }
1750n/a return seq;
1751n/a}
1752n/a
1753n/aPyDoc_STRVAR(version_info__doc__,
1754n/a"sys.version_info\n\
1755n/a\n\
1756n/aVersion information as a named tuple.");
1757n/a
1758n/astatic PyTypeObject VersionInfoType;
1759n/a
1760n/astatic PyStructSequence_Field version_info_fields[] = {
1761n/a {"major", "Major release number"},
1762n/a {"minor", "Minor release number"},
1763n/a {"micro", "Patch release number"},
1764n/a {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
1765n/a {"serial", "Serial release number"},
1766n/a {0}
1767n/a};
1768n/a
1769n/astatic PyStructSequence_Desc version_info_desc = {
1770n/a "sys.version_info", /* name */
1771n/a version_info__doc__, /* doc */
1772n/a version_info_fields, /* fields */
1773n/a 5
1774n/a};
1775n/a
1776n/astatic PyObject *
1777n/amake_version_info(void)
1778n/a{
1779n/a PyObject *version_info;
1780n/a char *s;
1781n/a int pos = 0;
1782n/a
1783n/a version_info = PyStructSequence_New(&VersionInfoType);
1784n/a if (version_info == NULL) {
1785n/a return NULL;
1786n/a }
1787n/a
1788n/a /*
1789n/a * These release level checks are mutually exclusive and cover
1790n/a * the field, so don't get too fancy with the pre-processor!
1791n/a */
1792n/a#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
1793n/a s = "alpha";
1794n/a#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
1795n/a s = "beta";
1796n/a#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
1797n/a s = "candidate";
1798n/a#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
1799n/a s = "final";
1800n/a#endif
1801n/a
1802n/a#define SetIntItem(flag) \
1803n/a PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
1804n/a#define SetStrItem(flag) \
1805n/a PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
1806n/a
1807n/a SetIntItem(PY_MAJOR_VERSION);
1808n/a SetIntItem(PY_MINOR_VERSION);
1809n/a SetIntItem(PY_MICRO_VERSION);
1810n/a SetStrItem(s);
1811n/a SetIntItem(PY_RELEASE_SERIAL);
1812n/a#undef SetIntItem
1813n/a#undef SetStrItem
1814n/a
1815n/a if (PyErr_Occurred()) {
1816n/a Py_CLEAR(version_info);
1817n/a return NULL;
1818n/a }
1819n/a return version_info;
1820n/a}
1821n/a
1822n/a/* sys.implementation values */
1823n/a#define NAME "cpython"
1824n/aconst char *_PySys_ImplName = NAME;
1825n/a#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
1826n/a#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
1827n/a#define TAG NAME "-" MAJOR MINOR
1828n/aconst char *_PySys_ImplCacheTag = TAG;
1829n/a#undef NAME
1830n/a#undef MAJOR
1831n/a#undef MINOR
1832n/a#undef TAG
1833n/a
1834n/astatic PyObject *
1835n/amake_impl_info(PyObject *version_info)
1836n/a{
1837n/a int res;
1838n/a PyObject *impl_info, *value, *ns;
1839n/a
1840n/a impl_info = PyDict_New();
1841n/a if (impl_info == NULL)
1842n/a return NULL;
1843n/a
1844n/a /* populate the dict */
1845n/a
1846n/a value = PyUnicode_FromString(_PySys_ImplName);
1847n/a if (value == NULL)
1848n/a goto error;
1849n/a res = PyDict_SetItemString(impl_info, "name", value);
1850n/a Py_DECREF(value);
1851n/a if (res < 0)
1852n/a goto error;
1853n/a
1854n/a value = PyUnicode_FromString(_PySys_ImplCacheTag);
1855n/a if (value == NULL)
1856n/a goto error;
1857n/a res = PyDict_SetItemString(impl_info, "cache_tag", value);
1858n/a Py_DECREF(value);
1859n/a if (res < 0)
1860n/a goto error;
1861n/a
1862n/a res = PyDict_SetItemString(impl_info, "version", version_info);
1863n/a if (res < 0)
1864n/a goto error;
1865n/a
1866n/a value = PyLong_FromLong(PY_VERSION_HEX);
1867n/a if (value == NULL)
1868n/a goto error;
1869n/a res = PyDict_SetItemString(impl_info, "hexversion", value);
1870n/a Py_DECREF(value);
1871n/a if (res < 0)
1872n/a goto error;
1873n/a
1874n/a#ifdef MULTIARCH
1875n/a value = PyUnicode_FromString(MULTIARCH);
1876n/a if (value == NULL)
1877n/a goto error;
1878n/a res = PyDict_SetItemString(impl_info, "_multiarch", value);
1879n/a Py_DECREF(value);
1880n/a if (res < 0)
1881n/a goto error;
1882n/a#endif
1883n/a
1884n/a /* dict ready */
1885n/a
1886n/a ns = _PyNamespace_New(impl_info);
1887n/a Py_DECREF(impl_info);
1888n/a return ns;
1889n/a
1890n/aerror:
1891n/a Py_CLEAR(impl_info);
1892n/a return NULL;
1893n/a}
1894n/a
1895n/astatic struct PyModuleDef sysmodule = {
1896n/a PyModuleDef_HEAD_INIT,
1897n/a "sys",
1898n/a sys_doc,
1899n/a -1, /* multiple "initialization" just copies the module dict. */
1900n/a sys_methods,
1901n/a NULL,
1902n/a NULL,
1903n/a NULL,
1904n/a NULL
1905n/a};
1906n/a
1907n/aPyObject *
1908n/a_PySys_Init(void)
1909n/a{
1910n/a PyObject *m, *sysdict, *version_info;
1911n/a int res;
1912n/a
1913n/a m = PyModule_Create(&sysmodule);
1914n/a if (m == NULL)
1915n/a return NULL;
1916n/a sysdict = PyModule_GetDict(m);
1917n/a#define SET_SYS_FROM_STRING_BORROW(key, value) \
1918n/a do { \
1919n/a PyObject *v = (value); \
1920n/a if (v == NULL) \
1921n/a return NULL; \
1922n/a res = PyDict_SetItemString(sysdict, key, v); \
1923n/a if (res < 0) { \
1924n/a return NULL; \
1925n/a } \
1926n/a } while (0)
1927n/a#define SET_SYS_FROM_STRING(key, value) \
1928n/a do { \
1929n/a PyObject *v = (value); \
1930n/a if (v == NULL) \
1931n/a return NULL; \
1932n/a res = PyDict_SetItemString(sysdict, key, v); \
1933n/a Py_DECREF(v); \
1934n/a if (res < 0) { \
1935n/a return NULL; \
1936n/a } \
1937n/a } while (0)
1938n/a
1939n/a /* Check that stdin is not a directory
1940n/a Using shell redirection, you can redirect stdin to a directory,
1941n/a crashing the Python interpreter. Catch this common mistake here
1942n/a and output a useful error message. Note that under MS Windows,
1943n/a the shell already prevents that. */
1944n/a#if !defined(MS_WINDOWS)
1945n/a {
1946n/a struct _Py_stat_struct sb;
1947n/a if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1948n/a S_ISDIR(sb.st_mode)) {
1949n/a /* There's nothing more we can do. */
1950n/a /* Py_FatalError() will core dump, so just exit. */
1951n/a PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1952n/a exit(EXIT_FAILURE);
1953n/a }
1954n/a }
1955n/a#endif
1956n/a
1957n/a /* stdin/stdout/stderr are set in pylifecycle.c */
1958n/a
1959n/a SET_SYS_FROM_STRING_BORROW("__displayhook__",
1960n/a PyDict_GetItemString(sysdict, "displayhook"));
1961n/a SET_SYS_FROM_STRING_BORROW("__excepthook__",
1962n/a PyDict_GetItemString(sysdict, "excepthook"));
1963n/a SET_SYS_FROM_STRING("version",
1964n/a PyUnicode_FromString(Py_GetVersion()));
1965n/a SET_SYS_FROM_STRING("hexversion",
1966n/a PyLong_FromLong(PY_VERSION_HEX));
1967n/a SET_SYS_FROM_STRING("_mercurial",
1968n/a Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),
1969n/a _Py_hgversion()));
1970n/a SET_SYS_FROM_STRING("dont_write_bytecode",
1971n/a PyBool_FromLong(Py_DontWriteBytecodeFlag));
1972n/a SET_SYS_FROM_STRING("api_version",
1973n/a PyLong_FromLong(PYTHON_API_VERSION));
1974n/a SET_SYS_FROM_STRING("copyright",
1975n/a PyUnicode_FromString(Py_GetCopyright()));
1976n/a SET_SYS_FROM_STRING("platform",
1977n/a PyUnicode_FromString(Py_GetPlatform()));
1978n/a SET_SYS_FROM_STRING("executable",
1979n/a PyUnicode_FromWideChar(
1980n/a Py_GetProgramFullPath(), -1));
1981n/a SET_SYS_FROM_STRING("prefix",
1982n/a PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1983n/a SET_SYS_FROM_STRING("exec_prefix",
1984n/a PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
1985n/a SET_SYS_FROM_STRING("base_prefix",
1986n/a PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1987n/a SET_SYS_FROM_STRING("base_exec_prefix",
1988n/a PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
1989n/a SET_SYS_FROM_STRING("maxsize",
1990n/a PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1991n/a SET_SYS_FROM_STRING("float_info",
1992n/a PyFloat_GetInfo());
1993n/a SET_SYS_FROM_STRING("int_info",
1994n/a PyLong_GetInfo());
1995n/a /* initialize hash_info */
1996n/a if (Hash_InfoType.tp_name == NULL) {
1997n/a if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
1998n/a return NULL;
1999n/a }
2000n/a SET_SYS_FROM_STRING("hash_info",
2001n/a get_hash_info());
2002n/a SET_SYS_FROM_STRING("maxunicode",
2003n/a PyLong_FromLong(0x10FFFF));
2004n/a SET_SYS_FROM_STRING("builtin_module_names",
2005n/a list_builtin_module_names());
2006n/a#if PY_BIG_ENDIAN
2007n/a SET_SYS_FROM_STRING("byteorder",
2008n/a PyUnicode_FromString("big"));
2009n/a#else
2010n/a SET_SYS_FROM_STRING("byteorder",
2011n/a PyUnicode_FromString("little"));
2012n/a#endif
2013n/a
2014n/a#ifdef MS_COREDLL
2015n/a SET_SYS_FROM_STRING("dllhandle",
2016n/a PyLong_FromVoidPtr(PyWin_DLLhModule));
2017n/a SET_SYS_FROM_STRING("winver",
2018n/a PyUnicode_FromString(PyWin_DLLVersionString));
2019n/a#endif
2020n/a#ifdef ABIFLAGS
2021n/a SET_SYS_FROM_STRING("abiflags",
2022n/a PyUnicode_FromString(ABIFLAGS));
2023n/a#endif
2024n/a if (warnoptions == NULL) {
2025n/a warnoptions = PyList_New(0);
2026n/a if (warnoptions == NULL)
2027n/a return NULL;
2028n/a }
2029n/a else {
2030n/a Py_INCREF(warnoptions);
2031n/a }
2032n/a SET_SYS_FROM_STRING_BORROW("warnoptions", warnoptions);
2033n/a
2034n/a SET_SYS_FROM_STRING_BORROW("_xoptions", get_xoptions());
2035n/a
2036n/a /* version_info */
2037n/a if (VersionInfoType.tp_name == NULL) {
2038n/a if (PyStructSequence_InitType2(&VersionInfoType,
2039n/a &version_info_desc) < 0)
2040n/a return NULL;
2041n/a }
2042n/a version_info = make_version_info();
2043n/a SET_SYS_FROM_STRING("version_info", version_info);
2044n/a /* prevent user from creating new instances */
2045n/a VersionInfoType.tp_init = NULL;
2046n/a VersionInfoType.tp_new = NULL;
2047n/a res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2048n/a if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2049n/a PyErr_Clear();
2050n/a
2051n/a /* implementation */
2052n/a SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2053n/a
2054n/a /* flags */
2055n/a if (FlagsType.tp_name == 0) {
2056n/a if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
2057n/a return NULL;
2058n/a }
2059n/a SET_SYS_FROM_STRING("flags", make_flags());
2060n/a /* prevent user from creating new instances */
2061n/a FlagsType.tp_init = NULL;
2062n/a FlagsType.tp_new = NULL;
2063n/a res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2064n/a if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2065n/a PyErr_Clear();
2066n/a
2067n/a#if defined(MS_WINDOWS)
2068n/a /* getwindowsversion */
2069n/a if (WindowsVersionType.tp_name == 0)
2070n/a if (PyStructSequence_InitType2(&WindowsVersionType,
2071n/a &windows_version_desc) < 0)
2072n/a return NULL;
2073n/a /* prevent user from creating new instances */
2074n/a WindowsVersionType.tp_init = NULL;
2075n/a WindowsVersionType.tp_new = NULL;
2076n/a res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
2077n/a if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2078n/a PyErr_Clear();
2079n/a#endif
2080n/a
2081n/a /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
2082n/a#ifndef PY_NO_SHORT_FLOAT_REPR
2083n/a SET_SYS_FROM_STRING("float_repr_style",
2084n/a PyUnicode_FromString("short"));
2085n/a#else
2086n/a SET_SYS_FROM_STRING("float_repr_style",
2087n/a PyUnicode_FromString("legacy"));
2088n/a#endif
2089n/a
2090n/a#ifdef WITH_THREAD
2091n/a SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
2092n/a#endif
2093n/a
2094n/a /* initialize asyncgen_hooks */
2095n/a if (AsyncGenHooksType.tp_name == NULL) {
2096n/a if (PyStructSequence_InitType2(
2097n/a &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
2098n/a return NULL;
2099n/a }
2100n/a }
2101n/a
2102n/a#undef SET_SYS_FROM_STRING
2103n/a#undef SET_SYS_FROM_STRING_BORROW
2104n/a if (PyErr_Occurred())
2105n/a return NULL;
2106n/a return m;
2107n/a}
2108n/a
2109n/astatic PyObject *
2110n/amakepathobject(const wchar_t *path, wchar_t delim)
2111n/a{
2112n/a int i, n;
2113n/a const wchar_t *p;
2114n/a PyObject *v, *w;
2115n/a
2116n/a n = 1;
2117n/a p = path;
2118n/a while ((p = wcschr(p, delim)) != NULL) {
2119n/a n++;
2120n/a p++;
2121n/a }
2122n/a v = PyList_New(n);
2123n/a if (v == NULL)
2124n/a return NULL;
2125n/a for (i = 0; ; i++) {
2126n/a p = wcschr(path, delim);
2127n/a if (p == NULL)
2128n/a p = path + wcslen(path); /* End of string */
2129n/a w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2130n/a if (w == NULL) {
2131n/a Py_DECREF(v);
2132n/a return NULL;
2133n/a }
2134n/a PyList_SetItem(v, i, w);
2135n/a if (*p == '\0')
2136n/a break;
2137n/a path = p+1;
2138n/a }
2139n/a return v;
2140n/a}
2141n/a
2142n/avoid
2143n/aPySys_SetPath(const wchar_t *path)
2144n/a{
2145n/a PyObject *v;
2146n/a if ((v = makepathobject(path, DELIM)) == NULL)
2147n/a Py_FatalError("can't create sys.path");
2148n/a if (_PySys_SetObjectId(&PyId_path, v) != 0)
2149n/a Py_FatalError("can't assign sys.path");
2150n/a Py_DECREF(v);
2151n/a}
2152n/a
2153n/astatic PyObject *
2154n/amakeargvobject(int argc, wchar_t **argv)
2155n/a{
2156n/a PyObject *av;
2157n/a if (argc <= 0 || argv == NULL) {
2158n/a /* Ensure at least one (empty) argument is seen */
2159n/a static wchar_t *empty_argv[1] = {L""};
2160n/a argv = empty_argv;
2161n/a argc = 1;
2162n/a }
2163n/a av = PyList_New(argc);
2164n/a if (av != NULL) {
2165n/a int i;
2166n/a for (i = 0; i < argc; i++) {
2167n/a PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
2168n/a if (v == NULL) {
2169n/a Py_DECREF(av);
2170n/a av = NULL;
2171n/a break;
2172n/a }
2173n/a PyList_SetItem(av, i, v);
2174n/a }
2175n/a }
2176n/a return av;
2177n/a}
2178n/a
2179n/a#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
2180n/a (argc > 0 && argv0 != NULL && \
2181n/a wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
2182n/a
2183n/astatic void
2184n/asys_update_path(int argc, wchar_t **argv)
2185n/a{
2186n/a wchar_t *argv0;
2187n/a wchar_t *p = NULL;
2188n/a Py_ssize_t n = 0;
2189n/a PyObject *a;
2190n/a PyObject *path;
2191n/a#ifdef HAVE_READLINK
2192n/a wchar_t link[MAXPATHLEN+1];
2193n/a wchar_t argv0copy[2*MAXPATHLEN+1];
2194n/a int nr = 0;
2195n/a#endif
2196n/a#if defined(HAVE_REALPATH)
2197n/a wchar_t fullpath[MAXPATHLEN];
2198n/a#elif defined(MS_WINDOWS)
2199n/a wchar_t fullpath[MAX_PATH];
2200n/a#endif
2201n/a
2202n/a path = _PySys_GetObjectId(&PyId_path);
2203n/a if (path == NULL)
2204n/a return;
2205n/a
2206n/a argv0 = argv[0];
2207n/a
2208n/a#ifdef HAVE_READLINK
2209n/a if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
2210n/a nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
2211n/a if (nr > 0) {
2212n/a /* It's a symlink */
2213n/a link[nr] = '\0';
2214n/a if (link[0] == SEP)
2215n/a argv0 = link; /* Link to absolute path */
2216n/a else if (wcschr(link, SEP) == NULL)
2217n/a ; /* Link without path */
2218n/a else {
2219n/a /* Must join(dirname(argv0), link) */
2220n/a wchar_t *q = wcsrchr(argv0, SEP);
2221n/a if (q == NULL)
2222n/a argv0 = link; /* argv0 without path */
2223n/a else {
2224n/a /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
2225n/a wcsncpy(argv0copy, argv0, MAXPATHLEN);
2226n/a q = wcsrchr(argv0copy, SEP);
2227n/a wcsncpy(q+1, link, MAXPATHLEN);
2228n/a q[MAXPATHLEN + 1] = L'\0';
2229n/a argv0 = argv0copy;
2230n/a }
2231n/a }
2232n/a }
2233n/a#endif /* HAVE_READLINK */
2234n/a#if SEP == '\\' /* Special case for MS filename syntax */
2235n/a if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2236n/a wchar_t *q;
2237n/a#if defined(MS_WINDOWS)
2238n/a /* Replace the first element in argv with the full path. */
2239n/a wchar_t *ptemp;
2240n/a if (GetFullPathNameW(argv0,
2241n/a Py_ARRAY_LENGTH(fullpath),
2242n/a fullpath,
2243n/a &ptemp)) {
2244n/a argv0 = fullpath;
2245n/a }
2246n/a#endif
2247n/a p = wcsrchr(argv0, SEP);
2248n/a /* Test for alternate separator */
2249n/a q = wcsrchr(p ? p : argv0, '/');
2250n/a if (q != NULL)
2251n/a p = q;
2252n/a if (p != NULL) {
2253n/a n = p + 1 - argv0;
2254n/a if (n > 1 && p[-1] != ':')
2255n/a n--; /* Drop trailing separator */
2256n/a }
2257n/a }
2258n/a#else /* All other filename syntaxes */
2259n/a if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2260n/a#if defined(HAVE_REALPATH)
2261n/a if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
2262n/a argv0 = fullpath;
2263n/a }
2264n/a#endif
2265n/a p = wcsrchr(argv0, SEP);
2266n/a }
2267n/a if (p != NULL) {
2268n/a n = p + 1 - argv0;
2269n/a#if SEP == '/' /* Special case for Unix filename syntax */
2270n/a if (n > 1)
2271n/a n--; /* Drop trailing separator */
2272n/a#endif /* Unix */
2273n/a }
2274n/a#endif /* All others */
2275n/a a = PyUnicode_FromWideChar(argv0, n);
2276n/a if (a == NULL)
2277n/a Py_FatalError("no mem for sys.path insertion");
2278n/a if (PyList_Insert(path, 0, a) < 0)
2279n/a Py_FatalError("sys.path.insert(0) failed");
2280n/a Py_DECREF(a);
2281n/a}
2282n/a
2283n/avoid
2284n/aPySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2285n/a{
2286n/a PyObject *av = makeargvobject(argc, argv);
2287n/a if (av == NULL)
2288n/a Py_FatalError("no mem for sys.argv");
2289n/a if (PySys_SetObject("argv", av) != 0)
2290n/a Py_FatalError("can't assign sys.argv");
2291n/a Py_DECREF(av);
2292n/a if (updatepath)
2293n/a sys_update_path(argc, argv);
2294n/a}
2295n/a
2296n/avoid
2297n/aPySys_SetArgv(int argc, wchar_t **argv)
2298n/a{
2299n/a PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
2300n/a}
2301n/a
2302n/a/* Reimplementation of PyFile_WriteString() no calling indirectly
2303n/a PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2304n/a
2305n/astatic int
2306n/asys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
2307n/a{
2308n/a PyObject *writer = NULL, *result = NULL;
2309n/a int err;
2310n/a
2311n/a if (file == NULL)
2312n/a return -1;
2313n/a
2314n/a writer = _PyObject_GetAttrId(file, &PyId_write);
2315n/a if (writer == NULL)
2316n/a goto error;
2317n/a
2318n/a result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
2319n/a if (result == NULL) {
2320n/a goto error;
2321n/a } else {
2322n/a err = 0;
2323n/a goto finally;
2324n/a }
2325n/a
2326n/aerror:
2327n/a err = -1;
2328n/afinally:
2329n/a Py_XDECREF(writer);
2330n/a Py_XDECREF(result);
2331n/a return err;
2332n/a}
2333n/a
2334n/astatic int
2335n/asys_pyfile_write(const char *text, PyObject *file)
2336n/a{
2337n/a PyObject *unicode = NULL;
2338n/a int err;
2339n/a
2340n/a if (file == NULL)
2341n/a return -1;
2342n/a
2343n/a unicode = PyUnicode_FromString(text);
2344n/a if (unicode == NULL)
2345n/a return -1;
2346n/a
2347n/a err = sys_pyfile_write_unicode(unicode, file);
2348n/a Py_DECREF(unicode);
2349n/a return err;
2350n/a}
2351n/a
2352n/a/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2353n/a Adapted from code submitted by Just van Rossum.
2354n/a
2355n/a PySys_WriteStdout(format, ...)
2356n/a PySys_WriteStderr(format, ...)
2357n/a
2358n/a The first function writes to sys.stdout; the second to sys.stderr. When
2359n/a there is a problem, they write to the real (C level) stdout or stderr;
2360n/a no exceptions are raised.
2361n/a
2362n/a PyErr_CheckSignals() is not called to avoid the execution of the Python
2363n/a signal handlers: they may raise a new exception whereas sys_write()
2364n/a ignores all exceptions.
2365n/a
2366n/a Both take a printf-style format string as their first argument followed
2367n/a by a variable length argument list determined by the format string.
2368n/a
2369n/a *** WARNING ***
2370n/a
2371n/a The format should limit the total size of the formatted output string to
2372n/a 1000 bytes. In particular, this means that no unrestricted "%s" formats
2373n/a should occur; these should be limited using "%.<N>s where <N> is a
2374n/a decimal number calculated so that <N> plus the maximum size of other
2375n/a formatted text does not exceed 1000 bytes. Also watch out for "%f",
2376n/a which can print hundreds of digits for very large numbers.
2377n/a
2378n/a */
2379n/a
2380n/astatic void
2381n/asys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
2382n/a{
2383n/a PyObject *file;
2384n/a PyObject *error_type, *error_value, *error_traceback;
2385n/a char buffer[1001];
2386n/a int written;
2387n/a
2388n/a PyErr_Fetch(&error_type, &error_value, &error_traceback);
2389n/a file = _PySys_GetObjectId(key);
2390n/a written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2391n/a if (sys_pyfile_write(buffer, file) != 0) {
2392n/a PyErr_Clear();
2393n/a fputs(buffer, fp);
2394n/a }
2395n/a if (written < 0 || (size_t)written >= sizeof(buffer)) {
2396n/a const char *truncated = "... truncated";
2397n/a if (sys_pyfile_write(truncated, file) != 0)
2398n/a fputs(truncated, fp);
2399n/a }
2400n/a PyErr_Restore(error_type, error_value, error_traceback);
2401n/a}
2402n/a
2403n/avoid
2404n/aPySys_WriteStdout(const char *format, ...)
2405n/a{
2406n/a va_list va;
2407n/a
2408n/a va_start(va, format);
2409n/a sys_write(&PyId_stdout, stdout, format, va);
2410n/a va_end(va);
2411n/a}
2412n/a
2413n/avoid
2414n/aPySys_WriteStderr(const char *format, ...)
2415n/a{
2416n/a va_list va;
2417n/a
2418n/a va_start(va, format);
2419n/a sys_write(&PyId_stderr, stderr, format, va);
2420n/a va_end(va);
2421n/a}
2422n/a
2423n/astatic void
2424n/asys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
2425n/a{
2426n/a PyObject *file, *message;
2427n/a PyObject *error_type, *error_value, *error_traceback;
2428n/a const char *utf8;
2429n/a
2430n/a PyErr_Fetch(&error_type, &error_value, &error_traceback);
2431n/a file = _PySys_GetObjectId(key);
2432n/a message = PyUnicode_FromFormatV(format, va);
2433n/a if (message != NULL) {
2434n/a if (sys_pyfile_write_unicode(message, file) != 0) {
2435n/a PyErr_Clear();
2436n/a utf8 = PyUnicode_AsUTF8(message);
2437n/a if (utf8 != NULL)
2438n/a fputs(utf8, fp);
2439n/a }
2440n/a Py_DECREF(message);
2441n/a }
2442n/a PyErr_Restore(error_type, error_value, error_traceback);
2443n/a}
2444n/a
2445n/avoid
2446n/aPySys_FormatStdout(const char *format, ...)
2447n/a{
2448n/a va_list va;
2449n/a
2450n/a va_start(va, format);
2451n/a sys_format(&PyId_stdout, stdout, format, va);
2452n/a va_end(va);
2453n/a}
2454n/a
2455n/avoid
2456n/aPySys_FormatStderr(const char *format, ...)
2457n/a{
2458n/a va_list va;
2459n/a
2460n/a va_start(va, format);
2461n/a sys_format(&PyId_stderr, stderr, format, va);
2462n/a va_end(va);
2463n/a}