You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2238 lines
61 KiB

36 years ago
bpo-36763: Implement the PEP 587 (GH-13592) * Add a whole new documentation page: "Python Initialization Configuration" * PyWideStringList_Append() return type is now PyStatus, instead of int * PyInterpreterState_New() now calls PyConfig_Clear() if PyConfig_InitPythonConfig() fails. * Rename files: * Python/coreconfig.c => Python/initconfig.c * Include/cpython/coreconfig.h => Include/cpython/initconfig.h * Include/internal/: pycore_coreconfig.h => pycore_initconfig.h * Rename structures * _PyCoreConfig => PyConfig * _PyPreConfig => PyPreConfig * _PyInitError => PyStatus * _PyWstrList => PyWideStringList * Rename PyConfig fields: * use_module_search_paths => module_search_paths_set * module_search_path_env => pythonpath_env * Rename PyStatus field: _func => func * PyInterpreterState: rename core_config field to config * Rename macros and functions: * _PyCoreConfig_SetArgv() => PyConfig_SetBytesArgv() * _PyCoreConfig_SetWideArgv() => PyConfig_SetArgv() * _PyCoreConfig_DecodeLocale() => PyConfig_SetBytesString() * _PyInitError_Failed() => PyStatus_Exception() * _Py_INIT_ERROR_TYPE_xxx enums => _PyStatus_TYPE_xxx * _Py_UnixMain() => Py_BytesMain() * _Py_ExitInitError() => Py_ExitStatusException() * _Py_PreInitializeFromArgs() => Py_PreInitializeFromBytesArgs() * _Py_PreInitializeFromWideArgs() => Py_PreInitializeFromArgs() * _Py_PreInitialize() => Py_PreInitialize() * _Py_RunMain() => Py_RunMain() * _Py_InitializeFromConfig() => Py_InitializeFromConfig() * _Py_INIT_XXX() => _PyStatus_XXX() * _Py_INIT_FAILED() => _PyStatus_EXCEPTION() * Rename 'err' PyStatus variables to 'status' * Convert RUN_CODE() macro to config_run_code() static inline function * Remove functions: * _Py_InitializeFromArgs() * _Py_InitializeFromWideArgs() * _PyInterpreterState_GetCoreConfig()
7 years ago
36 years ago
36 years ago
36 years ago
24 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
Merged revisions 53451-53537 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r53454 | brett.cannon | 2007-01-15 20:12:08 +0100 (Mon, 15 Jan 2007) | 3 lines Add a note for strptime that just because strftime supports some extra directive that is not documented that strptime will as well. ........ r53458 | vinay.sajip | 2007-01-16 10:50:07 +0100 (Tue, 16 Jan 2007) | 1 line Updated rotating file handlers to use _open(). ........ r53459 | marc-andre.lemburg | 2007-01-16 14:03:06 +0100 (Tue, 16 Jan 2007) | 2 lines Add news items for the recent pybench and platform changes. ........ r53460 | sjoerd.mullender | 2007-01-16 17:42:38 +0100 (Tue, 16 Jan 2007) | 4 lines Fixed ntpath.expandvars to not replace references to non-existing variables with nothing. Also added tests. This fixes bug #494589. ........ r53464 | neal.norwitz | 2007-01-17 07:23:51 +0100 (Wed, 17 Jan 2007) | 1 line Give Calvin Spealman access for python-dev summaries. ........ r53465 | neal.norwitz | 2007-01-17 09:37:26 +0100 (Wed, 17 Jan 2007) | 1 line Remove Calvin since he only has access to the website currently. ........ r53466 | thomas.heller | 2007-01-17 10:40:34 +0100 (Wed, 17 Jan 2007) | 2 lines Replace C++ comments with C comments. ........ r53472 | andrew.kuchling | 2007-01-17 20:55:06 +0100 (Wed, 17 Jan 2007) | 1 line [Part of bug #1599254] Add suggestion to Mailbox docs to use Maildir, and warn user to lock/unlock mailboxes when modifying them ........ r53475 | georg.brandl | 2007-01-17 22:09:04 +0100 (Wed, 17 Jan 2007) | 2 lines Bug #1637967: missing //= operator in list. ........ r53477 | georg.brandl | 2007-01-17 22:19:58 +0100 (Wed, 17 Jan 2007) | 2 lines Bug #1629125: fix wrong data type (int -> Py_ssize_t) in PyDict_Next docs. ........ r53481 | neal.norwitz | 2007-01-18 06:40:58 +0100 (Thu, 18 Jan 2007) | 1 line Try reverting part of r53145 that seems to cause the Windows buildbots to fail in test_uu.UUFileTest.test_encode ........ r53482 | fred.drake | 2007-01-18 06:42:30 +0100 (Thu, 18 Jan 2007) | 1 line add missing version entry ........ r53483 | neal.norwitz | 2007-01-18 07:20:55 +0100 (Thu, 18 Jan 2007) | 7 lines This test doesn't pass on Windows. The cause seems to be that chmod doesn't support the same funcationality as on Unix. I'm not sure if this fix is the best (or if it will even work)--it's a test to see if the buildbots start passing again. It might be better to not even run this test if it's windows (or non-posix). ........ r53488 | neal.norwitz | 2007-01-19 06:53:33 +0100 (Fri, 19 Jan 2007) | 1 line SF #1635217, Fix unbalanced paren ........ r53489 | martin.v.loewis | 2007-01-19 07:42:22 +0100 (Fri, 19 Jan 2007) | 3 lines Prefix AST symbols with _Py_. Fixes #1637022. Will backport. ........ r53497 | martin.v.loewis | 2007-01-19 19:01:38 +0100 (Fri, 19 Jan 2007) | 2 lines Add UUIDs for 2.5.1 and 2.5.2 ........ r53499 | raymond.hettinger | 2007-01-19 19:07:18 +0100 (Fri, 19 Jan 2007) | 1 line SF# 1635892: Fix docs for betavariate's input parameters . ........ r53503 | martin.v.loewis | 2007-01-20 15:05:39 +0100 (Sat, 20 Jan 2007) | 2 lines Merge 53501 and 53502 from 25 branch: Add /GS- for AMD64 and Itanium builds where missing. ........ r53504 | walter.doerwald | 2007-01-20 18:28:31 +0100 (Sat, 20 Jan 2007) | 2 lines Port test_resource.py to unittest. ........ r53505 | walter.doerwald | 2007-01-20 19:19:33 +0100 (Sat, 20 Jan 2007) | 2 lines Add argument tests an calls of resource.getrusage(). ........ r53506 | walter.doerwald | 2007-01-20 20:03:17 +0100 (Sat, 20 Jan 2007) | 2 lines resource.RUSAGE_BOTH might not exist. ........ r53507 | walter.doerwald | 2007-01-21 00:07:28 +0100 (Sun, 21 Jan 2007) | 2 lines Port test_new.py to unittest. ........ r53508 | martin.v.loewis | 2007-01-21 10:33:07 +0100 (Sun, 21 Jan 2007) | 2 lines Patch #1610575: Add support for _Bool to struct. ........ r53509 | georg.brandl | 2007-01-21 11:28:43 +0100 (Sun, 21 Jan 2007) | 3 lines Bug #1486663: don't reject keyword arguments for subclasses of builtin types. ........ r53511 | georg.brandl | 2007-01-21 11:35:10 +0100 (Sun, 21 Jan 2007) | 2 lines Patch #1627441: close sockets properly in urllib2. ........ r53517 | georg.brandl | 2007-01-22 20:40:21 +0100 (Mon, 22 Jan 2007) | 3 lines Use new email module names (#1637162, #1637159, #1637157). ........ r53518 | andrew.kuchling | 2007-01-22 21:26:40 +0100 (Mon, 22 Jan 2007) | 1 line Improve pattern used for mbox 'From' lines; add a simple test ........ r53519 | andrew.kuchling | 2007-01-22 21:27:50 +0100 (Mon, 22 Jan 2007) | 1 line Make comment match the code ........ r53522 | georg.brandl | 2007-01-22 22:10:33 +0100 (Mon, 22 Jan 2007) | 2 lines Bug #1249573: fix rfc822.parsedate not accepting a certain date format ........ r53524 | georg.brandl | 2007-01-22 22:23:41 +0100 (Mon, 22 Jan 2007) | 2 lines Bug #1627316: handle error in condition/ignore pdb commands more gracefully. ........ r53526 | lars.gustaebel | 2007-01-23 12:17:33 +0100 (Tue, 23 Jan 2007) | 4 lines Patch #1507247: tarfile.py: use current umask for intermediate directories. ........ r53527 | thomas.wouters | 2007-01-23 14:42:00 +0100 (Tue, 23 Jan 2007) | 13 lines SF patch #1630975: Fix crash when replacing sys.stdout in sitecustomize When running the interpreter in an environment that would cause it to set stdout/stderr/stdin's encoding, having a sitecustomize that would replace them with something other than PyFile objects would crash the interpreter. Fix it by simply ignoring the encoding-setting for non-files. This could do with a test, but I can think of no maintainable and portable way to test this bug, short of adding a sitecustomize.py to the buildsystem and have it always run with it (hmmm....) ........ r53528 | thomas.wouters | 2007-01-23 14:50:49 +0100 (Tue, 23 Jan 2007) | 4 lines Add news entry about last checkin (oops.) ........ r53531 | martin.v.loewis | 2007-01-23 22:11:47 +0100 (Tue, 23 Jan 2007) | 4 lines Make PyTraceBack_Here use the current thread, not the frame's thread state. Fixes #1579370. Will backport. ........ r53535 | brett.cannon | 2007-01-24 00:21:22 +0100 (Wed, 24 Jan 2007) | 5 lines Fix crasher for when an object's __del__ creates a new weakref to itself. Patch only fixes new-style classes; classic classes still buggy. Closes bug #1377858. Already backported. ........ r53536 | walter.doerwald | 2007-01-24 01:42:19 +0100 (Wed, 24 Jan 2007) | 2 lines Port test_popen.py to unittest. ........
20 years ago
36 years ago
Changes to recursive-object comparisons, having to do with a test case I found where rich comparison of unequal recursive objects gave unintuituve results. In a discussion with Tim, where we discovered that our intuition on when a<=b should be true was failing, we decided to outlaw ordering comparisons on recursive objects. (Once we have fixed our intuition and designed a matching algorithm that's practical and reasonable to implement, we can allow such orderings again.) - Refactored the recursive-object comparison framework; more is now done in the support routines so less needs to be done in the calling routines (even at the expense of slowing it down a bit -- this should normally never be invoked, it's mostly just there to avoid blowing up the interpreter). - Changed the framework so that the comparison operator used is also stored. (The dictionary now stores triples (v, w, op) instead of pairs (v, w).) - Changed the nesting limit to a more reasonable small 20; this only slows down comparisons of very deeply nested objects (unlikely to occur in practice), while speeding up comparisons of recursive objects (previously, this would first waste time and space on 500 nested comparisons before it would start detecting recursion). - Changed rich comparisons for recursive objects to raise a ValueError exception when recursion is detected for ordering oprators (<, <=, >, >=). Unrelated change: - Moved PyObject_Unicode() to just under PyObject_Str(), where it belongs. MAL's patch must've inserted in a random spot between two functions in the file -- between two helpers for rich comparison...
26 years ago
16 years ago
16 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
36 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
36 years ago
36 years ago
36 years ago
35 years ago
36 years ago
36 years ago
36 years ago
bpo-36763: Implement the PEP 587 (GH-13592) * Add a whole new documentation page: "Python Initialization Configuration" * PyWideStringList_Append() return type is now PyStatus, instead of int * PyInterpreterState_New() now calls PyConfig_Clear() if PyConfig_InitPythonConfig() fails. * Rename files: * Python/coreconfig.c => Python/initconfig.c * Include/cpython/coreconfig.h => Include/cpython/initconfig.h * Include/internal/: pycore_coreconfig.h => pycore_initconfig.h * Rename structures * _PyCoreConfig => PyConfig * _PyPreConfig => PyPreConfig * _PyInitError => PyStatus * _PyWstrList => PyWideStringList * Rename PyConfig fields: * use_module_search_paths => module_search_paths_set * module_search_path_env => pythonpath_env * Rename PyStatus field: _func => func * PyInterpreterState: rename core_config field to config * Rename macros and functions: * _PyCoreConfig_SetArgv() => PyConfig_SetBytesArgv() * _PyCoreConfig_SetWideArgv() => PyConfig_SetArgv() * _PyCoreConfig_DecodeLocale() => PyConfig_SetBytesString() * _PyInitError_Failed() => PyStatus_Exception() * _Py_INIT_ERROR_TYPE_xxx enums => _PyStatus_TYPE_xxx * _Py_UnixMain() => Py_BytesMain() * _Py_ExitInitError() => Py_ExitStatusException() * _Py_PreInitializeFromArgs() => Py_PreInitializeFromBytesArgs() * _Py_PreInitializeFromWideArgs() => Py_PreInitializeFromArgs() * _Py_PreInitialize() => Py_PreInitialize() * _Py_RunMain() => Py_RunMain() * _Py_InitializeFromConfig() => Py_InitializeFromConfig() * _Py_INIT_XXX() => _PyStatus_XXX() * _Py_INIT_FAILED() => _PyStatus_EXCEPTION() * Rename 'err' PyStatus variables to 'status' * Convert RUN_CODE() macro to config_run_code() static inline function * Remove functions: * _Py_InitializeFromArgs() * _Py_InitializeFromWideArgs() * _PyInterpreterState_GetCoreConfig()
7 years ago
bpo-36763: Implement the PEP 587 (GH-13592) * Add a whole new documentation page: "Python Initialization Configuration" * PyWideStringList_Append() return type is now PyStatus, instead of int * PyInterpreterState_New() now calls PyConfig_Clear() if PyConfig_InitPythonConfig() fails. * Rename files: * Python/coreconfig.c => Python/initconfig.c * Include/cpython/coreconfig.h => Include/cpython/initconfig.h * Include/internal/: pycore_coreconfig.h => pycore_initconfig.h * Rename structures * _PyCoreConfig => PyConfig * _PyPreConfig => PyPreConfig * _PyInitError => PyStatus * _PyWstrList => PyWideStringList * Rename PyConfig fields: * use_module_search_paths => module_search_paths_set * module_search_path_env => pythonpath_env * Rename PyStatus field: _func => func * PyInterpreterState: rename core_config field to config * Rename macros and functions: * _PyCoreConfig_SetArgv() => PyConfig_SetBytesArgv() * _PyCoreConfig_SetWideArgv() => PyConfig_SetArgv() * _PyCoreConfig_DecodeLocale() => PyConfig_SetBytesString() * _PyInitError_Failed() => PyStatus_Exception() * _Py_INIT_ERROR_TYPE_xxx enums => _PyStatus_TYPE_xxx * _Py_UnixMain() => Py_BytesMain() * _Py_ExitInitError() => Py_ExitStatusException() * _Py_PreInitializeFromArgs() => Py_PreInitializeFromBytesArgs() * _Py_PreInitializeFromWideArgs() => Py_PreInitializeFromArgs() * _Py_PreInitialize() => Py_PreInitialize() * _Py_RunMain() => Py_RunMain() * _Py_InitializeFromConfig() => Py_InitializeFromConfig() * _Py_INIT_XXX() => _PyStatus_XXX() * _Py_INIT_FAILED() => _PyStatus_EXCEPTION() * Rename 'err' PyStatus variables to 'status' * Convert RUN_CODE() macro to config_run_code() static inline function * Remove functions: * _Py_InitializeFromArgs() * _Py_InitializeFromWideArgs() * _PyInterpreterState_GetCoreConfig()
7 years ago
bpo-36763: Implement the PEP 587 (GH-13592) * Add a whole new documentation page: "Python Initialization Configuration" * PyWideStringList_Append() return type is now PyStatus, instead of int * PyInterpreterState_New() now calls PyConfig_Clear() if PyConfig_InitPythonConfig() fails. * Rename files: * Python/coreconfig.c => Python/initconfig.c * Include/cpython/coreconfig.h => Include/cpython/initconfig.h * Include/internal/: pycore_coreconfig.h => pycore_initconfig.h * Rename structures * _PyCoreConfig => PyConfig * _PyPreConfig => PyPreConfig * _PyInitError => PyStatus * _PyWstrList => PyWideStringList * Rename PyConfig fields: * use_module_search_paths => module_search_paths_set * module_search_path_env => pythonpath_env * Rename PyStatus field: _func => func * PyInterpreterState: rename core_config field to config * Rename macros and functions: * _PyCoreConfig_SetArgv() => PyConfig_SetBytesArgv() * _PyCoreConfig_SetWideArgv() => PyConfig_SetArgv() * _PyCoreConfig_DecodeLocale() => PyConfig_SetBytesString() * _PyInitError_Failed() => PyStatus_Exception() * _Py_INIT_ERROR_TYPE_xxx enums => _PyStatus_TYPE_xxx * _Py_UnixMain() => Py_BytesMain() * _Py_ExitInitError() => Py_ExitStatusException() * _Py_PreInitializeFromArgs() => Py_PreInitializeFromBytesArgs() * _Py_PreInitializeFromWideArgs() => Py_PreInitializeFromArgs() * _Py_PreInitialize() => Py_PreInitialize() * _Py_RunMain() => Py_RunMain() * _Py_InitializeFromConfig() => Py_InitializeFromConfig() * _Py_INIT_XXX() => _PyStatus_XXX() * _Py_INIT_FAILED() => _PyStatus_EXCEPTION() * Rename 'err' PyStatus variables to 'status' * Convert RUN_CODE() macro to config_run_code() static inline function * Remove functions: * _Py_InitializeFromArgs() * _Py_InitializeFromWideArgs() * _PyInterpreterState_GetCoreConfig()
7 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
  1. /* Generic object operations; and implementation of None */
  2. #include "Python.h"
  3. #include "pycore_ceval.h" // _Py_EnterRecursiveCall()
  4. #include "pycore_context.h"
  5. #include "pycore_initconfig.h"
  6. #include "pycore_object.h"
  7. #include "pycore_pyerrors.h"
  8. #include "pycore_pylifecycle.h"
  9. #include "pycore_pymem.h" // _PyMem_IsPtrFreed()
  10. #include "pycore_pystate.h" // _PyThreadState_GET()
  11. #include "frameobject.h"
  12. #include "interpreteridobject.h"
  13. #ifdef __cplusplus
  14. extern "C" {
  15. #endif
  16. /* Defined in tracemalloc.c */
  17. extern void _PyMem_DumpTraceback(int fd, const void *ptr);
  18. _Py_IDENTIFIER(Py_Repr);
  19. _Py_IDENTIFIER(__bytes__);
  20. _Py_IDENTIFIER(__dir__);
  21. _Py_IDENTIFIER(__isabstractmethod__);
  22. int
  23. _PyObject_CheckConsistency(PyObject *op, int check_content)
  24. {
  25. #define CHECK(expr) \
  26. do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
  27. CHECK(!_PyObject_IsFreed(op));
  28. CHECK(Py_REFCNT(op) >= 1);
  29. _PyType_CheckConsistency(Py_TYPE(op));
  30. if (PyUnicode_Check(op)) {
  31. _PyUnicode_CheckConsistency(op, check_content);
  32. }
  33. else if (PyDict_Check(op)) {
  34. _PyDict_CheckConsistency(op, check_content);
  35. }
  36. return 1;
  37. #undef CHECK
  38. }
  39. #ifdef Py_REF_DEBUG
  40. Py_ssize_t _Py_RefTotal;
  41. Py_ssize_t
  42. _Py_GetRefTotal(void)
  43. {
  44. PyObject *o;
  45. Py_ssize_t total = _Py_RefTotal;
  46. o = _PySet_Dummy;
  47. if (o != NULL)
  48. total -= Py_REFCNT(o);
  49. return total;
  50. }
  51. void
  52. _PyDebug_PrintTotalRefs(void) {
  53. fprintf(stderr,
  54. "[%zd refs, %zd blocks]\n",
  55. _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
  56. }
  57. #endif /* Py_REF_DEBUG */
  58. /* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
  59. These are used by the individual routines for object creation.
  60. Do not call them otherwise, they do not initialize the object! */
  61. #ifdef Py_TRACE_REFS
  62. /* Head of circular doubly-linked list of all objects. These are linked
  63. * together via the _ob_prev and _ob_next members of a PyObject, which
  64. * exist only in a Py_TRACE_REFS build.
  65. */
  66. static PyObject refchain = {&refchain, &refchain};
  67. /* Insert op at the front of the list of all objects. If force is true,
  68. * op is added even if _ob_prev and _ob_next are non-NULL already. If
  69. * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
  70. * force should be true if and only if op points to freshly allocated,
  71. * uninitialized memory, or you've unlinked op from the list and are
  72. * relinking it into the front.
  73. * Note that objects are normally added to the list via _Py_NewReference,
  74. * which is called by PyObject_Init. Not all objects are initialized that
  75. * way, though; exceptions include statically allocated type objects, and
  76. * statically allocated singletons (like Py_True and Py_None).
  77. */
  78. void
  79. _Py_AddToAllObjects(PyObject *op, int force)
  80. {
  81. #ifdef Py_DEBUG
  82. if (!force) {
  83. /* If it's initialized memory, op must be in or out of
  84. * the list unambiguously.
  85. */
  86. _PyObject_ASSERT(op, (op->_ob_prev == NULL) == (op->_ob_next == NULL));
  87. }
  88. #endif
  89. if (force || op->_ob_prev == NULL) {
  90. op->_ob_next = refchain._ob_next;
  91. op->_ob_prev = &refchain;
  92. refchain._ob_next->_ob_prev = op;
  93. refchain._ob_next = op;
  94. }
  95. }
  96. #endif /* Py_TRACE_REFS */
  97. #ifdef Py_REF_DEBUG
  98. /* Log a fatal error; doesn't return. */
  99. void
  100. _Py_NegativeRefcount(const char *filename, int lineno, PyObject *op)
  101. {
  102. _PyObject_AssertFailed(op, NULL, "object has negative ref count",
  103. filename, lineno, __func__);
  104. }
  105. #endif /* Py_REF_DEBUG */
  106. void
  107. Py_IncRef(PyObject *o)
  108. {
  109. Py_XINCREF(o);
  110. }
  111. void
  112. Py_DecRef(PyObject *o)
  113. {
  114. Py_XDECREF(o);
  115. }
  116. PyObject *
  117. PyObject_Init(PyObject *op, PyTypeObject *tp)
  118. {
  119. if (op == NULL) {
  120. return PyErr_NoMemory();
  121. }
  122. _PyObject_Init(op, tp);
  123. return op;
  124. }
  125. PyVarObject *
  126. PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
  127. {
  128. if (op == NULL) {
  129. return (PyVarObject *) PyErr_NoMemory();
  130. }
  131. _PyObject_InitVar(op, tp, size);
  132. return op;
  133. }
  134. PyObject *
  135. _PyObject_New(PyTypeObject *tp)
  136. {
  137. PyObject *op = (PyObject *) PyObject_Malloc(_PyObject_SIZE(tp));
  138. if (op == NULL) {
  139. return PyErr_NoMemory();
  140. }
  141. _PyObject_Init(op, tp);
  142. return op;
  143. }
  144. PyVarObject *
  145. _PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
  146. {
  147. PyVarObject *op;
  148. const size_t size = _PyObject_VAR_SIZE(tp, nitems);
  149. op = (PyVarObject *) PyObject_Malloc(size);
  150. if (op == NULL) {
  151. return (PyVarObject *)PyErr_NoMemory();
  152. }
  153. _PyObject_InitVar(op, tp, nitems);
  154. return op;
  155. }
  156. void
  157. PyObject_CallFinalizer(PyObject *self)
  158. {
  159. PyTypeObject *tp = Py_TYPE(self);
  160. if (tp->tp_finalize == NULL)
  161. return;
  162. /* tp_finalize should only be called once. */
  163. if (_PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
  164. return;
  165. tp->tp_finalize(self);
  166. if (_PyType_IS_GC(tp)) {
  167. _PyGC_SET_FINALIZED(self);
  168. }
  169. }
  170. int
  171. PyObject_CallFinalizerFromDealloc(PyObject *self)
  172. {
  173. if (Py_REFCNT(self) != 0) {
  174. _PyObject_ASSERT_FAILED_MSG(self,
  175. "PyObject_CallFinalizerFromDealloc called "
  176. "on object with a non-zero refcount");
  177. }
  178. /* Temporarily resurrect the object. */
  179. Py_SET_REFCNT(self, 1);
  180. PyObject_CallFinalizer(self);
  181. _PyObject_ASSERT_WITH_MSG(self,
  182. Py_REFCNT(self) > 0,
  183. "refcount is too small");
  184. /* Undo the temporary resurrection; can't use DECREF here, it would
  185. * cause a recursive call. */
  186. Py_SET_REFCNT(self, Py_REFCNT(self) - 1);
  187. if (Py_REFCNT(self) == 0) {
  188. return 0; /* this is the normal path out */
  189. }
  190. /* tp_finalize resurrected it! Make it look like the original Py_DECREF
  191. * never happened. */
  192. Py_ssize_t refcnt = Py_REFCNT(self);
  193. _Py_NewReference(self);
  194. Py_SET_REFCNT(self, refcnt);
  195. _PyObject_ASSERT(self,
  196. (!_PyType_IS_GC(Py_TYPE(self))
  197. || _PyObject_GC_IS_TRACKED(self)));
  198. /* If Py_REF_DEBUG macro is defined, _Py_NewReference() increased
  199. _Py_RefTotal, so we need to undo that. */
  200. #ifdef Py_REF_DEBUG
  201. _Py_RefTotal--;
  202. #endif
  203. return -1;
  204. }
  205. int
  206. PyObject_Print(PyObject *op, FILE *fp, int flags)
  207. {
  208. int ret = 0;
  209. if (PyErr_CheckSignals())
  210. return -1;
  211. #ifdef USE_STACKCHECK
  212. if (PyOS_CheckStack()) {
  213. PyErr_SetString(PyExc_MemoryError, "stack overflow");
  214. return -1;
  215. }
  216. #endif
  217. clearerr(fp); /* Clear any previous error condition */
  218. if (op == NULL) {
  219. Py_BEGIN_ALLOW_THREADS
  220. fprintf(fp, "<nil>");
  221. Py_END_ALLOW_THREADS
  222. }
  223. else {
  224. if (Py_REFCNT(op) <= 0) {
  225. /* XXX(twouters) cast refcount to long until %zd is
  226. universally available */
  227. Py_BEGIN_ALLOW_THREADS
  228. fprintf(fp, "<refcnt %ld at %p>",
  229. (long)Py_REFCNT(op), (void *)op);
  230. Py_END_ALLOW_THREADS
  231. }
  232. else {
  233. PyObject *s;
  234. if (flags & Py_PRINT_RAW)
  235. s = PyObject_Str(op);
  236. else
  237. s = PyObject_Repr(op);
  238. if (s == NULL)
  239. ret = -1;
  240. else if (PyBytes_Check(s)) {
  241. fwrite(PyBytes_AS_STRING(s), 1,
  242. PyBytes_GET_SIZE(s), fp);
  243. }
  244. else if (PyUnicode_Check(s)) {
  245. PyObject *t;
  246. t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
  247. if (t == NULL) {
  248. ret = -1;
  249. }
  250. else {
  251. fwrite(PyBytes_AS_STRING(t), 1,
  252. PyBytes_GET_SIZE(t), fp);
  253. Py_DECREF(t);
  254. }
  255. }
  256. else {
  257. PyErr_Format(PyExc_TypeError,
  258. "str() or repr() returned '%.100s'",
  259. Py_TYPE(s)->tp_name);
  260. ret = -1;
  261. }
  262. Py_XDECREF(s);
  263. }
  264. }
  265. if (ret == 0) {
  266. if (ferror(fp)) {
  267. PyErr_SetFromErrno(PyExc_OSError);
  268. clearerr(fp);
  269. ret = -1;
  270. }
  271. }
  272. return ret;
  273. }
  274. /* For debugging convenience. Set a breakpoint here and call it from your DLL */
  275. void
  276. _Py_BreakPoint(void)
  277. {
  278. }
  279. /* Heuristic checking if the object memory is uninitialized or deallocated.
  280. Rely on the debug hooks on Python memory allocators:
  281. see _PyMem_IsPtrFreed().
  282. The function can be used to prevent segmentation fault on dereferencing
  283. pointers like 0xDDDDDDDDDDDDDDDD. */
  284. int
  285. _PyObject_IsFreed(PyObject *op)
  286. {
  287. if (_PyMem_IsPtrFreed(op) || _PyMem_IsPtrFreed(Py_TYPE(op))) {
  288. return 1;
  289. }
  290. /* ignore op->ob_ref: its value can have be modified
  291. by Py_INCREF() and Py_DECREF(). */
  292. #ifdef Py_TRACE_REFS
  293. if (op->_ob_next != NULL && _PyMem_IsPtrFreed(op->_ob_next)) {
  294. return 1;
  295. }
  296. if (op->_ob_prev != NULL && _PyMem_IsPtrFreed(op->_ob_prev)) {
  297. return 1;
  298. }
  299. #endif
  300. return 0;
  301. }
  302. /* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
  303. void
  304. _PyObject_Dump(PyObject* op)
  305. {
  306. if (_PyObject_IsFreed(op)) {
  307. /* It seems like the object memory has been freed:
  308. don't access it to prevent a segmentation fault. */
  309. fprintf(stderr, "<object at %p is freed>\n", op);
  310. fflush(stderr);
  311. return;
  312. }
  313. /* first, write fields which are the least likely to crash */
  314. fprintf(stderr, "object address : %p\n", (void *)op);
  315. /* XXX(twouters) cast refcount to long until %zd is
  316. universally available */
  317. fprintf(stderr, "object refcount : %ld\n", (long)Py_REFCNT(op));
  318. fflush(stderr);
  319. PyTypeObject *type = Py_TYPE(op);
  320. fprintf(stderr, "object type : %p\n", type);
  321. fprintf(stderr, "object type name: %s\n",
  322. type==NULL ? "NULL" : type->tp_name);
  323. /* the most dangerous part */
  324. fprintf(stderr, "object repr : ");
  325. fflush(stderr);
  326. PyGILState_STATE gil = PyGILState_Ensure();
  327. PyObject *error_type, *error_value, *error_traceback;
  328. PyErr_Fetch(&error_type, &error_value, &error_traceback);
  329. (void)PyObject_Print(op, stderr, 0);
  330. fflush(stderr);
  331. PyErr_Restore(error_type, error_value, error_traceback);
  332. PyGILState_Release(gil);
  333. fprintf(stderr, "\n");
  334. fflush(stderr);
  335. }
  336. PyObject *
  337. PyObject_Repr(PyObject *v)
  338. {
  339. PyObject *res;
  340. if (PyErr_CheckSignals())
  341. return NULL;
  342. #ifdef USE_STACKCHECK
  343. if (PyOS_CheckStack()) {
  344. PyErr_SetString(PyExc_MemoryError, "stack overflow");
  345. return NULL;
  346. }
  347. #endif
  348. if (v == NULL)
  349. return PyUnicode_FromString("<NULL>");
  350. if (Py_TYPE(v)->tp_repr == NULL)
  351. return PyUnicode_FromFormat("<%s object at %p>",
  352. Py_TYPE(v)->tp_name, v);
  353. PyThreadState *tstate = _PyThreadState_GET();
  354. #ifdef Py_DEBUG
  355. /* PyObject_Repr() must not be called with an exception set,
  356. because it can clear it (directly or indirectly) and so the
  357. caller loses its exception */
  358. assert(!_PyErr_Occurred(tstate));
  359. #endif
  360. /* It is possible for a type to have a tp_repr representation that loops
  361. infinitely. */
  362. if (_Py_EnterRecursiveCall(tstate,
  363. " while getting the repr of an object")) {
  364. return NULL;
  365. }
  366. res = (*Py_TYPE(v)->tp_repr)(v);
  367. _Py_LeaveRecursiveCall(tstate);
  368. if (res == NULL) {
  369. return NULL;
  370. }
  371. if (!PyUnicode_Check(res)) {
  372. _PyErr_Format(tstate, PyExc_TypeError,
  373. "__repr__ returned non-string (type %.200s)",
  374. Py_TYPE(res)->tp_name);
  375. Py_DECREF(res);
  376. return NULL;
  377. }
  378. #ifndef Py_DEBUG
  379. if (PyUnicode_READY(res) < 0) {
  380. return NULL;
  381. }
  382. #endif
  383. return res;
  384. }
  385. PyObject *
  386. PyObject_Str(PyObject *v)
  387. {
  388. PyObject *res;
  389. if (PyErr_CheckSignals())
  390. return NULL;
  391. #ifdef USE_STACKCHECK
  392. if (PyOS_CheckStack()) {
  393. PyErr_SetString(PyExc_MemoryError, "stack overflow");
  394. return NULL;
  395. }
  396. #endif
  397. if (v == NULL)
  398. return PyUnicode_FromString("<NULL>");
  399. if (PyUnicode_CheckExact(v)) {
  400. #ifndef Py_DEBUG
  401. if (PyUnicode_READY(v) < 0)
  402. return NULL;
  403. #endif
  404. Py_INCREF(v);
  405. return v;
  406. }
  407. if (Py_TYPE(v)->tp_str == NULL)
  408. return PyObject_Repr(v);
  409. PyThreadState *tstate = _PyThreadState_GET();
  410. #ifdef Py_DEBUG
  411. /* PyObject_Str() must not be called with an exception set,
  412. because it can clear it (directly or indirectly) and so the
  413. caller loses its exception */
  414. assert(!_PyErr_Occurred(tstate));
  415. #endif
  416. /* It is possible for a type to have a tp_str representation that loops
  417. infinitely. */
  418. if (_Py_EnterRecursiveCall(tstate, " while getting the str of an object")) {
  419. return NULL;
  420. }
  421. res = (*Py_TYPE(v)->tp_str)(v);
  422. _Py_LeaveRecursiveCall(tstate);
  423. if (res == NULL) {
  424. return NULL;
  425. }
  426. if (!PyUnicode_Check(res)) {
  427. _PyErr_Format(tstate, PyExc_TypeError,
  428. "__str__ returned non-string (type %.200s)",
  429. Py_TYPE(res)->tp_name);
  430. Py_DECREF(res);
  431. return NULL;
  432. }
  433. #ifndef Py_DEBUG
  434. if (PyUnicode_READY(res) < 0) {
  435. return NULL;
  436. }
  437. #endif
  438. assert(_PyUnicode_CheckConsistency(res, 1));
  439. return res;
  440. }
  441. PyObject *
  442. PyObject_ASCII(PyObject *v)
  443. {
  444. PyObject *repr, *ascii, *res;
  445. repr = PyObject_Repr(v);
  446. if (repr == NULL)
  447. return NULL;
  448. if (PyUnicode_IS_ASCII(repr))
  449. return repr;
  450. /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
  451. ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
  452. Py_DECREF(repr);
  453. if (ascii == NULL)
  454. return NULL;
  455. res = PyUnicode_DecodeASCII(
  456. PyBytes_AS_STRING(ascii),
  457. PyBytes_GET_SIZE(ascii),
  458. NULL);
  459. Py_DECREF(ascii);
  460. return res;
  461. }
  462. PyObject *
  463. PyObject_Bytes(PyObject *v)
  464. {
  465. PyObject *result, *func;
  466. if (v == NULL)
  467. return PyBytes_FromString("<NULL>");
  468. if (PyBytes_CheckExact(v)) {
  469. Py_INCREF(v);
  470. return v;
  471. }
  472. func = _PyObject_LookupSpecial(v, &PyId___bytes__);
  473. if (func != NULL) {
  474. result = _PyObject_CallNoArg(func);
  475. Py_DECREF(func);
  476. if (result == NULL)
  477. return NULL;
  478. if (!PyBytes_Check(result)) {
  479. PyErr_Format(PyExc_TypeError,
  480. "__bytes__ returned non-bytes (type %.200s)",
  481. Py_TYPE(result)->tp_name);
  482. Py_DECREF(result);
  483. return NULL;
  484. }
  485. return result;
  486. }
  487. else if (PyErr_Occurred())
  488. return NULL;
  489. return PyBytes_FromObject(v);
  490. }
  491. /*
  492. def _PyObject_FunctionStr(x):
  493. try:
  494. qualname = x.__qualname__
  495. except AttributeError:
  496. return str(x)
  497. try:
  498. mod = x.__module__
  499. if mod is not None and mod != 'builtins':
  500. return f"{x.__module__}.{qualname}()"
  501. except AttributeError:
  502. pass
  503. return qualname
  504. */
  505. PyObject *
  506. _PyObject_FunctionStr(PyObject *x)
  507. {
  508. _Py_IDENTIFIER(__module__);
  509. _Py_IDENTIFIER(__qualname__);
  510. _Py_IDENTIFIER(builtins);
  511. assert(!PyErr_Occurred());
  512. PyObject *qualname;
  513. int ret = _PyObject_LookupAttrId(x, &PyId___qualname__, &qualname);
  514. if (qualname == NULL) {
  515. if (ret < 0) {
  516. return NULL;
  517. }
  518. return PyObject_Str(x);
  519. }
  520. PyObject *module;
  521. PyObject *result = NULL;
  522. ret = _PyObject_LookupAttrId(x, &PyId___module__, &module);
  523. if (module != NULL && module != Py_None) {
  524. PyObject *builtinsname = _PyUnicode_FromId(&PyId_builtins);
  525. if (builtinsname == NULL) {
  526. goto done;
  527. }
  528. ret = PyObject_RichCompareBool(module, builtinsname, Py_NE);
  529. if (ret < 0) {
  530. // error
  531. goto done;
  532. }
  533. if (ret > 0) {
  534. result = PyUnicode_FromFormat("%S.%S()", module, qualname);
  535. goto done;
  536. }
  537. }
  538. else if (ret < 0) {
  539. goto done;
  540. }
  541. result = PyUnicode_FromFormat("%S()", qualname);
  542. done:
  543. Py_DECREF(qualname);
  544. Py_XDECREF(module);
  545. return result;
  546. }
  547. /* For Python 3.0.1 and later, the old three-way comparison has been
  548. completely removed in favour of rich comparisons. PyObject_Compare() and
  549. PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
  550. The old tp_compare slot has been renamed to tp_as_async, and should no
  551. longer be used. Use tp_richcompare instead.
  552. See (*) below for practical amendments.
  553. tp_richcompare gets called with a first argument of the appropriate type
  554. and a second object of an arbitrary type. We never do any kind of
  555. coercion.
  556. The tp_richcompare slot should return an object, as follows:
  557. NULL if an exception occurred
  558. NotImplemented if the requested comparison is not implemented
  559. any other false value if the requested comparison is false
  560. any other true value if the requested comparison is true
  561. The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
  562. NotImplemented.
  563. (*) Practical amendments:
  564. - If rich comparison returns NotImplemented, == and != are decided by
  565. comparing the object pointer (i.e. falling back to the base object
  566. implementation).
  567. */
  568. /* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
  569. int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
  570. static const char * const opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
  571. /* Perform a rich comparison, raising TypeError when the requested comparison
  572. operator is not supported. */
  573. static PyObject *
  574. do_richcompare(PyThreadState *tstate, PyObject *v, PyObject *w, int op)
  575. {
  576. richcmpfunc f;
  577. PyObject *res;
  578. int checked_reverse_op = 0;
  579. if (!Py_IS_TYPE(v, Py_TYPE(w)) &&
  580. PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v)) &&
  581. (f = Py_TYPE(w)->tp_richcompare) != NULL) {
  582. checked_reverse_op = 1;
  583. res = (*f)(w, v, _Py_SwappedOp[op]);
  584. if (res != Py_NotImplemented)
  585. return res;
  586. Py_DECREF(res);
  587. }
  588. if ((f = Py_TYPE(v)->tp_richcompare) != NULL) {
  589. res = (*f)(v, w, op);
  590. if (res != Py_NotImplemented)
  591. return res;
  592. Py_DECREF(res);
  593. }
  594. if (!checked_reverse_op && (f = Py_TYPE(w)->tp_richcompare) != NULL) {
  595. res = (*f)(w, v, _Py_SwappedOp[op]);
  596. if (res != Py_NotImplemented)
  597. return res;
  598. Py_DECREF(res);
  599. }
  600. /* If neither object implements it, provide a sensible default
  601. for == and !=, but raise an exception for ordering. */
  602. switch (op) {
  603. case Py_EQ:
  604. res = (v == w) ? Py_True : Py_False;
  605. break;
  606. case Py_NE:
  607. res = (v != w) ? Py_True : Py_False;
  608. break;
  609. default:
  610. _PyErr_Format(tstate, PyExc_TypeError,
  611. "'%s' not supported between instances of '%.100s' and '%.100s'",
  612. opstrings[op],
  613. Py_TYPE(v)->tp_name,
  614. Py_TYPE(w)->tp_name);
  615. return NULL;
  616. }
  617. Py_INCREF(res);
  618. return res;
  619. }
  620. /* Perform a rich comparison with object result. This wraps do_richcompare()
  621. with a check for NULL arguments and a recursion check. */
  622. PyObject *
  623. PyObject_RichCompare(PyObject *v, PyObject *w, int op)
  624. {
  625. PyThreadState *tstate = _PyThreadState_GET();
  626. assert(Py_LT <= op && op <= Py_GE);
  627. if (v == NULL || w == NULL) {
  628. if (!_PyErr_Occurred(tstate)) {
  629. PyErr_BadInternalCall();
  630. }
  631. return NULL;
  632. }
  633. if (_Py_EnterRecursiveCall(tstate, " in comparison")) {
  634. return NULL;
  635. }
  636. PyObject *res = do_richcompare(tstate, v, w, op);
  637. _Py_LeaveRecursiveCall(tstate);
  638. return res;
  639. }
  640. /* Perform a rich comparison with integer result. This wraps
  641. PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
  642. int
  643. PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
  644. {
  645. PyObject *res;
  646. int ok;
  647. /* Quick result when objects are the same.
  648. Guarantees that identity implies equality. */
  649. if (v == w) {
  650. if (op == Py_EQ)
  651. return 1;
  652. else if (op == Py_NE)
  653. return 0;
  654. }
  655. res = PyObject_RichCompare(v, w, op);
  656. if (res == NULL)
  657. return -1;
  658. if (PyBool_Check(res))
  659. ok = (res == Py_True);
  660. else
  661. ok = PyObject_IsTrue(res);
  662. Py_DECREF(res);
  663. return ok;
  664. }
  665. Py_hash_t
  666. PyObject_HashNotImplemented(PyObject *v)
  667. {
  668. PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
  669. Py_TYPE(v)->tp_name);
  670. return -1;
  671. }
  672. Py_hash_t
  673. PyObject_Hash(PyObject *v)
  674. {
  675. PyTypeObject *tp = Py_TYPE(v);
  676. if (tp->tp_hash != NULL)
  677. return (*tp->tp_hash)(v);
  678. /* To keep to the general practice that inheriting
  679. * solely from object in C code should work without
  680. * an explicit call to PyType_Ready, we implicitly call
  681. * PyType_Ready here and then check the tp_hash slot again
  682. */
  683. if (tp->tp_dict == NULL) {
  684. if (PyType_Ready(tp) < 0)
  685. return -1;
  686. if (tp->tp_hash != NULL)
  687. return (*tp->tp_hash)(v);
  688. }
  689. /* Otherwise, the object can't be hashed */
  690. return PyObject_HashNotImplemented(v);
  691. }
  692. PyObject *
  693. PyObject_GetAttrString(PyObject *v, const char *name)
  694. {
  695. PyObject *w, *res;
  696. if (Py_TYPE(v)->tp_getattr != NULL)
  697. return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
  698. w = PyUnicode_FromString(name);
  699. if (w == NULL)
  700. return NULL;
  701. res = PyObject_GetAttr(v, w);
  702. Py_DECREF(w);
  703. return res;
  704. }
  705. int
  706. PyObject_HasAttrString(PyObject *v, const char *name)
  707. {
  708. PyObject *res = PyObject_GetAttrString(v, name);
  709. if (res != NULL) {
  710. Py_DECREF(res);
  711. return 1;
  712. }
  713. PyErr_Clear();
  714. return 0;
  715. }
  716. int
  717. PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
  718. {
  719. PyObject *s;
  720. int res;
  721. if (Py_TYPE(v)->tp_setattr != NULL)
  722. return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
  723. s = PyUnicode_InternFromString(name);
  724. if (s == NULL)
  725. return -1;
  726. res = PyObject_SetAttr(v, s, w);
  727. Py_XDECREF(s);
  728. return res;
  729. }
  730. int
  731. _PyObject_IsAbstract(PyObject *obj)
  732. {
  733. int res;
  734. PyObject* isabstract;
  735. if (obj == NULL)
  736. return 0;
  737. res = _PyObject_LookupAttrId(obj, &PyId___isabstractmethod__, &isabstract);
  738. if (res > 0) {
  739. res = PyObject_IsTrue(isabstract);
  740. Py_DECREF(isabstract);
  741. }
  742. return res;
  743. }
  744. PyObject *
  745. _PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
  746. {
  747. PyObject *result;
  748. PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
  749. if (!oname)
  750. return NULL;
  751. result = PyObject_GetAttr(v, oname);
  752. return result;
  753. }
  754. int
  755. _PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
  756. {
  757. int result;
  758. PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
  759. if (!oname)
  760. return -1;
  761. result = PyObject_SetAttr(v, oname, w);
  762. return result;
  763. }
  764. PyObject *
  765. PyObject_GetAttr(PyObject *v, PyObject *name)
  766. {
  767. PyTypeObject *tp = Py_TYPE(v);
  768. if (!PyUnicode_Check(name)) {
  769. PyErr_Format(PyExc_TypeError,
  770. "attribute name must be string, not '%.200s'",
  771. Py_TYPE(name)->tp_name);
  772. return NULL;
  773. }
  774. if (tp->tp_getattro != NULL)
  775. return (*tp->tp_getattro)(v, name);
  776. if (tp->tp_getattr != NULL) {
  777. const char *name_str = PyUnicode_AsUTF8(name);
  778. if (name_str == NULL)
  779. return NULL;
  780. return (*tp->tp_getattr)(v, (char *)name_str);
  781. }
  782. PyErr_Format(PyExc_AttributeError,
  783. "'%.50s' object has no attribute '%U'",
  784. tp->tp_name, name);
  785. return NULL;
  786. }
  787. int
  788. _PyObject_LookupAttr(PyObject *v, PyObject *name, PyObject **result)
  789. {
  790. PyTypeObject *tp = Py_TYPE(v);
  791. if (!PyUnicode_Check(name)) {
  792. PyErr_Format(PyExc_TypeError,
  793. "attribute name must be string, not '%.200s'",
  794. Py_TYPE(name)->tp_name);
  795. *result = NULL;
  796. return -1;
  797. }
  798. if (tp->tp_getattro == PyObject_GenericGetAttr) {
  799. *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
  800. if (*result != NULL) {
  801. return 1;
  802. }
  803. if (PyErr_Occurred()) {
  804. return -1;
  805. }
  806. return 0;
  807. }
  808. if (tp->tp_getattro != NULL) {
  809. *result = (*tp->tp_getattro)(v, name);
  810. }
  811. else if (tp->tp_getattr != NULL) {
  812. const char *name_str = PyUnicode_AsUTF8(name);
  813. if (name_str == NULL) {
  814. *result = NULL;
  815. return -1;
  816. }
  817. *result = (*tp->tp_getattr)(v, (char *)name_str);
  818. }
  819. else {
  820. *result = NULL;
  821. return 0;
  822. }
  823. if (*result != NULL) {
  824. return 1;
  825. }
  826. if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
  827. return -1;
  828. }
  829. PyErr_Clear();
  830. return 0;
  831. }
  832. int
  833. _PyObject_LookupAttrId(PyObject *v, _Py_Identifier *name, PyObject **result)
  834. {
  835. PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
  836. if (!oname) {
  837. *result = NULL;
  838. return -1;
  839. }
  840. return _PyObject_LookupAttr(v, oname, result);
  841. }
  842. int
  843. PyObject_HasAttr(PyObject *v, PyObject *name)
  844. {
  845. PyObject *res;
  846. if (_PyObject_LookupAttr(v, name, &res) < 0) {
  847. PyErr_Clear();
  848. return 0;
  849. }
  850. if (res == NULL) {
  851. return 0;
  852. }
  853. Py_DECREF(res);
  854. return 1;
  855. }
  856. int
  857. PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
  858. {
  859. PyTypeObject *tp = Py_TYPE(v);
  860. int err;
  861. if (!PyUnicode_Check(name)) {
  862. PyErr_Format(PyExc_TypeError,
  863. "attribute name must be string, not '%.200s'",
  864. Py_TYPE(name)->tp_name);
  865. return -1;
  866. }
  867. Py_INCREF(name);
  868. PyUnicode_InternInPlace(&name);
  869. if (tp->tp_setattro != NULL) {
  870. err = (*tp->tp_setattro)(v, name, value);
  871. Py_DECREF(name);
  872. return err;
  873. }
  874. if (tp->tp_setattr != NULL) {
  875. const char *name_str = PyUnicode_AsUTF8(name);
  876. if (name_str == NULL) {
  877. Py_DECREF(name);
  878. return -1;
  879. }
  880. err = (*tp->tp_setattr)(v, (char *)name_str, value);
  881. Py_DECREF(name);
  882. return err;
  883. }
  884. Py_DECREF(name);
  885. _PyObject_ASSERT(name, Py_REFCNT(name) >= 1);
  886. if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
  887. PyErr_Format(PyExc_TypeError,
  888. "'%.100s' object has no attributes "
  889. "(%s .%U)",
  890. tp->tp_name,
  891. value==NULL ? "del" : "assign to",
  892. name);
  893. else
  894. PyErr_Format(PyExc_TypeError,
  895. "'%.100s' object has only read-only attributes "
  896. "(%s .%U)",
  897. tp->tp_name,
  898. value==NULL ? "del" : "assign to",
  899. name);
  900. return -1;
  901. }
  902. /* Helper to get a pointer to an object's __dict__ slot, if any */
  903. PyObject **
  904. _PyObject_GetDictPtr(PyObject *obj)
  905. {
  906. Py_ssize_t dictoffset;
  907. PyTypeObject *tp = Py_TYPE(obj);
  908. dictoffset = tp->tp_dictoffset;
  909. if (dictoffset == 0)
  910. return NULL;
  911. if (dictoffset < 0) {
  912. Py_ssize_t tsize = Py_SIZE(obj);
  913. if (tsize < 0) {
  914. tsize = -tsize;
  915. }
  916. size_t size = _PyObject_VAR_SIZE(tp, tsize);
  917. dictoffset += (long)size;
  918. _PyObject_ASSERT(obj, dictoffset > 0);
  919. _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
  920. }
  921. return (PyObject **) ((char *)obj + dictoffset);
  922. }
  923. PyObject *
  924. PyObject_SelfIter(PyObject *obj)
  925. {
  926. Py_INCREF(obj);
  927. return obj;
  928. }
  929. /* Helper used when the __next__ method is removed from a type:
  930. tp_iternext is never NULL and can be safely called without checking
  931. on every iteration.
  932. */
  933. PyObject *
  934. _PyObject_NextNotImplemented(PyObject *self)
  935. {
  936. PyErr_Format(PyExc_TypeError,
  937. "'%.200s' object is not iterable",
  938. Py_TYPE(self)->tp_name);
  939. return NULL;
  940. }
  941. /* Specialized version of _PyObject_GenericGetAttrWithDict
  942. specifically for the LOAD_METHOD opcode.
  943. Return 1 if a method is found, 0 if it's a regular attribute
  944. from __dict__ or something returned by using a descriptor
  945. protocol.
  946. `method` will point to the resolved attribute or NULL. In the
  947. latter case, an error will be set.
  948. */
  949. int
  950. _PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method)
  951. {
  952. PyTypeObject *tp = Py_TYPE(obj);
  953. PyObject *descr;
  954. descrgetfunc f = NULL;
  955. PyObject **dictptr, *dict;
  956. PyObject *attr;
  957. int meth_found = 0;
  958. assert(*method == NULL);
  959. if (Py_TYPE(obj)->tp_getattro != PyObject_GenericGetAttr
  960. || !PyUnicode_Check(name)) {
  961. *method = PyObject_GetAttr(obj, name);
  962. return 0;
  963. }
  964. if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
  965. return 0;
  966. descr = _PyType_Lookup(tp, name);
  967. if (descr != NULL) {
  968. Py_INCREF(descr);
  969. if (_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) {
  970. meth_found = 1;
  971. } else {
  972. f = Py_TYPE(descr)->tp_descr_get;
  973. if (f != NULL && PyDescr_IsData(descr)) {
  974. *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
  975. Py_DECREF(descr);
  976. return 0;
  977. }
  978. }
  979. }
  980. dictptr = _PyObject_GetDictPtr(obj);
  981. if (dictptr != NULL && (dict = *dictptr) != NULL) {
  982. Py_INCREF(dict);
  983. attr = PyDict_GetItemWithError(dict, name);
  984. if (attr != NULL) {
  985. Py_INCREF(attr);
  986. *method = attr;
  987. Py_DECREF(dict);
  988. Py_XDECREF(descr);
  989. return 0;
  990. }
  991. else {
  992. Py_DECREF(dict);
  993. if (PyErr_Occurred()) {
  994. Py_XDECREF(descr);
  995. return 0;
  996. }
  997. }
  998. }
  999. if (meth_found) {
  1000. *method = descr;
  1001. return 1;
  1002. }
  1003. if (f != NULL) {
  1004. *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
  1005. Py_DECREF(descr);
  1006. return 0;
  1007. }
  1008. if (descr != NULL) {
  1009. *method = descr;
  1010. return 0;
  1011. }
  1012. PyErr_Format(PyExc_AttributeError,
  1013. "'%.50s' object has no attribute '%U'",
  1014. tp->tp_name, name);
  1015. return 0;
  1016. }
  1017. /* Generic GetAttr functions - put these in your tp_[gs]etattro slot. */
  1018. PyObject *
  1019. _PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name,
  1020. PyObject *dict, int suppress)
  1021. {
  1022. /* Make sure the logic of _PyObject_GetMethod is in sync with
  1023. this method.
  1024. When suppress=1, this function suppresses AttributeError.
  1025. */
  1026. PyTypeObject *tp = Py_TYPE(obj);
  1027. PyObject *descr = NULL;
  1028. PyObject *res = NULL;
  1029. descrgetfunc f;
  1030. Py_ssize_t dictoffset;
  1031. PyObject **dictptr;
  1032. if (!PyUnicode_Check(name)){
  1033. PyErr_Format(PyExc_TypeError,
  1034. "attribute name must be string, not '%.200s'",
  1035. Py_TYPE(name)->tp_name);
  1036. return NULL;
  1037. }
  1038. Py_INCREF(name);
  1039. if (tp->tp_dict == NULL) {
  1040. if (PyType_Ready(tp) < 0)
  1041. goto done;
  1042. }
  1043. descr = _PyType_Lookup(tp, name);
  1044. f = NULL;
  1045. if (descr != NULL) {
  1046. Py_INCREF(descr);
  1047. f = Py_TYPE(descr)->tp_descr_get;
  1048. if (f != NULL && PyDescr_IsData(descr)) {
  1049. res = f(descr, obj, (PyObject *)Py_TYPE(obj));
  1050. if (res == NULL && suppress &&
  1051. PyErr_ExceptionMatches(PyExc_AttributeError)) {
  1052. PyErr_Clear();
  1053. }
  1054. goto done;
  1055. }
  1056. }
  1057. if (dict == NULL) {
  1058. /* Inline _PyObject_GetDictPtr */
  1059. dictoffset = tp->tp_dictoffset;
  1060. if (dictoffset != 0) {
  1061. if (dictoffset < 0) {
  1062. Py_ssize_t tsize = Py_SIZE(obj);
  1063. if (tsize < 0) {
  1064. tsize = -tsize;
  1065. }
  1066. size_t size = _PyObject_VAR_SIZE(tp, tsize);
  1067. _PyObject_ASSERT(obj, size <= PY_SSIZE_T_MAX);
  1068. dictoffset += (Py_ssize_t)size;
  1069. _PyObject_ASSERT(obj, dictoffset > 0);
  1070. _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
  1071. }
  1072. dictptr = (PyObject **) ((char *)obj + dictoffset);
  1073. dict = *dictptr;
  1074. }
  1075. }
  1076. if (dict != NULL) {
  1077. Py_INCREF(dict);
  1078. res = PyDict_GetItemWithError(dict, name);
  1079. if (res != NULL) {
  1080. Py_INCREF(res);
  1081. Py_DECREF(dict);
  1082. goto done;
  1083. }
  1084. else {
  1085. Py_DECREF(dict);
  1086. if (PyErr_Occurred()) {
  1087. if (suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) {
  1088. PyErr_Clear();
  1089. }
  1090. else {
  1091. goto done;
  1092. }
  1093. }
  1094. }
  1095. }
  1096. if (f != NULL) {
  1097. res = f(descr, obj, (PyObject *)Py_TYPE(obj));
  1098. if (res == NULL && suppress &&
  1099. PyErr_ExceptionMatches(PyExc_AttributeError)) {
  1100. PyErr_Clear();
  1101. }
  1102. goto done;
  1103. }
  1104. if (descr != NULL) {
  1105. res = descr;
  1106. descr = NULL;
  1107. goto done;
  1108. }
  1109. if (!suppress) {
  1110. PyErr_Format(PyExc_AttributeError,
  1111. "'%.50s' object has no attribute '%U'",
  1112. tp->tp_name, name);
  1113. }
  1114. done:
  1115. Py_XDECREF(descr);
  1116. Py_DECREF(name);
  1117. return res;
  1118. }
  1119. PyObject *
  1120. PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
  1121. {
  1122. return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
  1123. }
  1124. int
  1125. _PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
  1126. PyObject *value, PyObject *dict)
  1127. {
  1128. PyTypeObject *tp = Py_TYPE(obj);
  1129. PyObject *descr;
  1130. descrsetfunc f;
  1131. PyObject **dictptr;
  1132. int res = -1;
  1133. if (!PyUnicode_Check(name)){
  1134. PyErr_Format(PyExc_TypeError,
  1135. "attribute name must be string, not '%.200s'",
  1136. Py_TYPE(name)->tp_name);
  1137. return -1;
  1138. }
  1139. if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
  1140. return -1;
  1141. Py_INCREF(name);
  1142. descr = _PyType_Lookup(tp, name);
  1143. if (descr != NULL) {
  1144. Py_INCREF(descr);
  1145. f = Py_TYPE(descr)->tp_descr_set;
  1146. if (f != NULL) {
  1147. res = f(descr, obj, value);
  1148. goto done;
  1149. }
  1150. }
  1151. /* XXX [Steve Dower] These are really noisy - worth it? */
  1152. /*if (PyType_Check(obj) || PyModule_Check(obj)) {
  1153. if (value && PySys_Audit("object.__setattr__", "OOO", obj, name, value) < 0)
  1154. return -1;
  1155. if (!value && PySys_Audit("object.__delattr__", "OO", obj, name) < 0)
  1156. return -1;
  1157. }*/
  1158. if (dict == NULL) {
  1159. dictptr = _PyObject_GetDictPtr(obj);
  1160. if (dictptr == NULL) {
  1161. if (descr == NULL) {
  1162. PyErr_Format(PyExc_AttributeError,
  1163. "'%.100s' object has no attribute '%U'",
  1164. tp->tp_name, name);
  1165. }
  1166. else {
  1167. PyErr_Format(PyExc_AttributeError,
  1168. "'%.50s' object attribute '%U' is read-only",
  1169. tp->tp_name, name);
  1170. }
  1171. goto done;
  1172. }
  1173. res = _PyObjectDict_SetItem(tp, dictptr, name, value);
  1174. }
  1175. else {
  1176. Py_INCREF(dict);
  1177. if (value == NULL)
  1178. res = PyDict_DelItem(dict, name);
  1179. else
  1180. res = PyDict_SetItem(dict, name, value);
  1181. Py_DECREF(dict);
  1182. }
  1183. if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
  1184. PyErr_SetObject(PyExc_AttributeError, name);
  1185. done:
  1186. Py_XDECREF(descr);
  1187. Py_DECREF(name);
  1188. return res;
  1189. }
  1190. int
  1191. PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
  1192. {
  1193. return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
  1194. }
  1195. int
  1196. PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
  1197. {
  1198. PyObject **dictptr = _PyObject_GetDictPtr(obj);
  1199. if (dictptr == NULL) {
  1200. PyErr_SetString(PyExc_AttributeError,
  1201. "This object has no __dict__");
  1202. return -1;
  1203. }
  1204. if (value == NULL) {
  1205. PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
  1206. return -1;
  1207. }
  1208. if (!PyDict_Check(value)) {
  1209. PyErr_Format(PyExc_TypeError,
  1210. "__dict__ must be set to a dictionary, "
  1211. "not a '%.200s'", Py_TYPE(value)->tp_name);
  1212. return -1;
  1213. }
  1214. Py_INCREF(value);
  1215. Py_XSETREF(*dictptr, value);
  1216. return 0;
  1217. }
  1218. /* Test a value used as condition, e.g., in a while or if statement.
  1219. Return -1 if an error occurred */
  1220. int
  1221. PyObject_IsTrue(PyObject *v)
  1222. {
  1223. Py_ssize_t res;
  1224. if (v == Py_True)
  1225. return 1;
  1226. if (v == Py_False)
  1227. return 0;
  1228. if (v == Py_None)
  1229. return 0;
  1230. else if (Py_TYPE(v)->tp_as_number != NULL &&
  1231. Py_TYPE(v)->tp_as_number->nb_bool != NULL)
  1232. res = (*Py_TYPE(v)->tp_as_number->nb_bool)(v);
  1233. else if (Py_TYPE(v)->tp_as_mapping != NULL &&
  1234. Py_TYPE(v)->tp_as_mapping->mp_length != NULL)
  1235. res = (*Py_TYPE(v)->tp_as_mapping->mp_length)(v);
  1236. else if (Py_TYPE(v)->tp_as_sequence != NULL &&
  1237. Py_TYPE(v)->tp_as_sequence->sq_length != NULL)
  1238. res = (*Py_TYPE(v)->tp_as_sequence->sq_length)(v);
  1239. else
  1240. return 1;
  1241. /* if it is negative, it should be either -1 or -2 */
  1242. return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
  1243. }
  1244. /* equivalent of 'not v'
  1245. Return -1 if an error occurred */
  1246. int
  1247. PyObject_Not(PyObject *v)
  1248. {
  1249. int res;
  1250. res = PyObject_IsTrue(v);
  1251. if (res < 0)
  1252. return res;
  1253. return res == 0;
  1254. }
  1255. /* Test whether an object can be called */
  1256. int
  1257. PyCallable_Check(PyObject *x)
  1258. {
  1259. if (x == NULL)
  1260. return 0;
  1261. return Py_TYPE(x)->tp_call != NULL;
  1262. }
  1263. /* Helper for PyObject_Dir without arguments: returns the local scope. */
  1264. static PyObject *
  1265. _dir_locals(void)
  1266. {
  1267. PyObject *names;
  1268. PyObject *locals;
  1269. locals = PyEval_GetLocals();
  1270. if (locals == NULL)
  1271. return NULL;
  1272. names = PyMapping_Keys(locals);
  1273. if (!names)
  1274. return NULL;
  1275. if (!PyList_Check(names)) {
  1276. PyErr_Format(PyExc_TypeError,
  1277. "dir(): expected keys() of locals to be a list, "
  1278. "not '%.200s'", Py_TYPE(names)->tp_name);
  1279. Py_DECREF(names);
  1280. return NULL;
  1281. }
  1282. if (PyList_Sort(names)) {
  1283. Py_DECREF(names);
  1284. return NULL;
  1285. }
  1286. /* the locals don't need to be DECREF'd */
  1287. return names;
  1288. }
  1289. /* Helper for PyObject_Dir: object introspection. */
  1290. static PyObject *
  1291. _dir_object(PyObject *obj)
  1292. {
  1293. PyObject *result, *sorted;
  1294. PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
  1295. assert(obj != NULL);
  1296. if (dirfunc == NULL) {
  1297. if (!PyErr_Occurred())
  1298. PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
  1299. return NULL;
  1300. }
  1301. /* use __dir__ */
  1302. result = _PyObject_CallNoArg(dirfunc);
  1303. Py_DECREF(dirfunc);
  1304. if (result == NULL)
  1305. return NULL;
  1306. /* return sorted(result) */
  1307. sorted = PySequence_List(result);
  1308. Py_DECREF(result);
  1309. if (sorted == NULL)
  1310. return NULL;
  1311. if (PyList_Sort(sorted)) {
  1312. Py_DECREF(sorted);
  1313. return NULL;
  1314. }
  1315. return sorted;
  1316. }
  1317. /* Implementation of dir() -- if obj is NULL, returns the names in the current
  1318. (local) scope. Otherwise, performs introspection of the object: returns a
  1319. sorted list of attribute names (supposedly) accessible from the object
  1320. */
  1321. PyObject *
  1322. PyObject_Dir(PyObject *obj)
  1323. {
  1324. return (obj == NULL) ? _dir_locals() : _dir_object(obj);
  1325. }
  1326. /*
  1327. None is a non-NULL undefined value.
  1328. There is (and should be!) no way to create other objects of this type,
  1329. so there is exactly one (which is indestructible, by the way).
  1330. */
  1331. /* ARGSUSED */
  1332. static PyObject *
  1333. none_repr(PyObject *op)
  1334. {
  1335. return PyUnicode_FromString("None");
  1336. }
  1337. /* ARGUSED */
  1338. static void _Py_NO_RETURN
  1339. none_dealloc(PyObject* ignore)
  1340. {
  1341. /* This should never get called, but we also don't want to SEGV if
  1342. * we accidentally decref None out of existence.
  1343. */
  1344. Py_FatalError("deallocating None");
  1345. }
  1346. static PyObject *
  1347. none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
  1348. {
  1349. if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
  1350. PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
  1351. return NULL;
  1352. }
  1353. Py_RETURN_NONE;
  1354. }
  1355. static int
  1356. none_bool(PyObject *v)
  1357. {
  1358. return 0;
  1359. }
  1360. static PyNumberMethods none_as_number = {
  1361. 0, /* nb_add */
  1362. 0, /* nb_subtract */
  1363. 0, /* nb_multiply */
  1364. 0, /* nb_remainder */
  1365. 0, /* nb_divmod */
  1366. 0, /* nb_power */
  1367. 0, /* nb_negative */
  1368. 0, /* nb_positive */
  1369. 0, /* nb_absolute */
  1370. (inquiry)none_bool, /* nb_bool */
  1371. 0, /* nb_invert */
  1372. 0, /* nb_lshift */
  1373. 0, /* nb_rshift */
  1374. 0, /* nb_and */
  1375. 0, /* nb_xor */
  1376. 0, /* nb_or */
  1377. 0, /* nb_int */
  1378. 0, /* nb_reserved */
  1379. 0, /* nb_float */
  1380. 0, /* nb_inplace_add */
  1381. 0, /* nb_inplace_subtract */
  1382. 0, /* nb_inplace_multiply */
  1383. 0, /* nb_inplace_remainder */
  1384. 0, /* nb_inplace_power */
  1385. 0, /* nb_inplace_lshift */
  1386. 0, /* nb_inplace_rshift */
  1387. 0, /* nb_inplace_and */
  1388. 0, /* nb_inplace_xor */
  1389. 0, /* nb_inplace_or */
  1390. 0, /* nb_floor_divide */
  1391. 0, /* nb_true_divide */
  1392. 0, /* nb_inplace_floor_divide */
  1393. 0, /* nb_inplace_true_divide */
  1394. 0, /* nb_index */
  1395. };
  1396. PyTypeObject _PyNone_Type = {
  1397. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1398. "NoneType",
  1399. 0,
  1400. 0,
  1401. none_dealloc, /*tp_dealloc*/ /*never called*/
  1402. 0, /*tp_vectorcall_offset*/
  1403. 0, /*tp_getattr*/
  1404. 0, /*tp_setattr*/
  1405. 0, /*tp_as_async*/
  1406. none_repr, /*tp_repr*/
  1407. &none_as_number, /*tp_as_number*/
  1408. 0, /*tp_as_sequence*/
  1409. 0, /*tp_as_mapping*/
  1410. 0, /*tp_hash */
  1411. 0, /*tp_call */
  1412. 0, /*tp_str */
  1413. 0, /*tp_getattro */
  1414. 0, /*tp_setattro */
  1415. 0, /*tp_as_buffer */
  1416. Py_TPFLAGS_DEFAULT, /*tp_flags */
  1417. 0, /*tp_doc */
  1418. 0, /*tp_traverse */
  1419. 0, /*tp_clear */
  1420. 0, /*tp_richcompare */
  1421. 0, /*tp_weaklistoffset */
  1422. 0, /*tp_iter */
  1423. 0, /*tp_iternext */
  1424. 0, /*tp_methods */
  1425. 0, /*tp_members */
  1426. 0, /*tp_getset */
  1427. 0, /*tp_base */
  1428. 0, /*tp_dict */
  1429. 0, /*tp_descr_get */
  1430. 0, /*tp_descr_set */
  1431. 0, /*tp_dictoffset */
  1432. 0, /*tp_init */
  1433. 0, /*tp_alloc */
  1434. none_new, /*tp_new */
  1435. };
  1436. PyObject _Py_NoneStruct = {
  1437. _PyObject_EXTRA_INIT
  1438. 1, &_PyNone_Type
  1439. };
  1440. /* NotImplemented is an object that can be used to signal that an
  1441. operation is not implemented for the given type combination. */
  1442. static PyObject *
  1443. NotImplemented_repr(PyObject *op)
  1444. {
  1445. return PyUnicode_FromString("NotImplemented");
  1446. }
  1447. static PyObject *
  1448. NotImplemented_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
  1449. {
  1450. return PyUnicode_FromString("NotImplemented");
  1451. }
  1452. static PyMethodDef notimplemented_methods[] = {
  1453. {"__reduce__", NotImplemented_reduce, METH_NOARGS, NULL},
  1454. {NULL, NULL}
  1455. };
  1456. static PyObject *
  1457. notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
  1458. {
  1459. if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
  1460. PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
  1461. return NULL;
  1462. }
  1463. Py_RETURN_NOTIMPLEMENTED;
  1464. }
  1465. static void _Py_NO_RETURN
  1466. notimplemented_dealloc(PyObject* ignore)
  1467. {
  1468. /* This should never get called, but we also don't want to SEGV if
  1469. * we accidentally decref NotImplemented out of existence.
  1470. */
  1471. Py_FatalError("deallocating NotImplemented");
  1472. }
  1473. static int
  1474. notimplemented_bool(PyObject *v)
  1475. {
  1476. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  1477. "NotImplemented should not be used in a boolean context",
  1478. 1) < 0)
  1479. {
  1480. return -1;
  1481. }
  1482. return 1;
  1483. }
  1484. static PyNumberMethods notimplemented_as_number = {
  1485. .nb_bool = notimplemented_bool,
  1486. };
  1487. PyTypeObject _PyNotImplemented_Type = {
  1488. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1489. "NotImplementedType",
  1490. 0,
  1491. 0,
  1492. notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
  1493. 0, /*tp_vectorcall_offset*/
  1494. 0, /*tp_getattr*/
  1495. 0, /*tp_setattr*/
  1496. 0, /*tp_as_async*/
  1497. NotImplemented_repr, /*tp_repr*/
  1498. &notimplemented_as_number, /*tp_as_number*/
  1499. 0, /*tp_as_sequence*/
  1500. 0, /*tp_as_mapping*/
  1501. 0, /*tp_hash */
  1502. 0, /*tp_call */
  1503. 0, /*tp_str */
  1504. 0, /*tp_getattro */
  1505. 0, /*tp_setattro */
  1506. 0, /*tp_as_buffer */
  1507. Py_TPFLAGS_DEFAULT, /*tp_flags */
  1508. 0, /*tp_doc */
  1509. 0, /*tp_traverse */
  1510. 0, /*tp_clear */
  1511. 0, /*tp_richcompare */
  1512. 0, /*tp_weaklistoffset */
  1513. 0, /*tp_iter */
  1514. 0, /*tp_iternext */
  1515. notimplemented_methods, /*tp_methods */
  1516. 0, /*tp_members */
  1517. 0, /*tp_getset */
  1518. 0, /*tp_base */
  1519. 0, /*tp_dict */
  1520. 0, /*tp_descr_get */
  1521. 0, /*tp_descr_set */
  1522. 0, /*tp_dictoffset */
  1523. 0, /*tp_init */
  1524. 0, /*tp_alloc */
  1525. notimplemented_new, /*tp_new */
  1526. };
  1527. PyObject _Py_NotImplementedStruct = {
  1528. _PyObject_EXTRA_INIT
  1529. 1, &_PyNotImplemented_Type
  1530. };
  1531. PyStatus
  1532. _PyTypes_Init(void)
  1533. {
  1534. PyStatus status = _PyTypes_InitSlotDefs();
  1535. if (_PyStatus_EXCEPTION(status)) {
  1536. return status;
  1537. }
  1538. #define INIT_TYPE(TYPE, NAME) \
  1539. do { \
  1540. if (PyType_Ready(TYPE) < 0) { \
  1541. return _PyStatus_ERR("Can't initialize " NAME " type"); \
  1542. } \
  1543. } while (0)
  1544. INIT_TYPE(&PyBaseObject_Type, "object");
  1545. INIT_TYPE(&PyType_Type, "type");
  1546. INIT_TYPE(&_PyWeakref_RefType, "weakref");
  1547. INIT_TYPE(&_PyWeakref_CallableProxyType, "callable weakref proxy");
  1548. INIT_TYPE(&_PyWeakref_ProxyType, "weakref proxy");
  1549. INIT_TYPE(&PyLong_Type, "int");
  1550. INIT_TYPE(&PyBool_Type, "bool");
  1551. INIT_TYPE(&PyByteArray_Type, "bytearray");
  1552. INIT_TYPE(&PyBytes_Type, "str");
  1553. INIT_TYPE(&PyList_Type, "list");
  1554. INIT_TYPE(&_PyNone_Type, "None");
  1555. INIT_TYPE(&_PyNotImplemented_Type, "NotImplemented");
  1556. INIT_TYPE(&PyTraceBack_Type, "traceback");
  1557. INIT_TYPE(&PySuper_Type, "super");
  1558. INIT_TYPE(&PyRange_Type, "range");
  1559. INIT_TYPE(&PyDict_Type, "dict");
  1560. INIT_TYPE(&PyDictKeys_Type, "dict keys");
  1561. INIT_TYPE(&PyDictValues_Type, "dict values");
  1562. INIT_TYPE(&PyDictItems_Type, "dict items");
  1563. INIT_TYPE(&PyDictRevIterKey_Type, "reversed dict keys");
  1564. INIT_TYPE(&PyDictRevIterValue_Type, "reversed dict values");
  1565. INIT_TYPE(&PyDictRevIterItem_Type, "reversed dict items");
  1566. INIT_TYPE(&PyODict_Type, "OrderedDict");
  1567. INIT_TYPE(&PyODictKeys_Type, "odict_keys");
  1568. INIT_TYPE(&PyODictItems_Type, "odict_items");
  1569. INIT_TYPE(&PyODictValues_Type, "odict_values");
  1570. INIT_TYPE(&PyODictIter_Type, "odict_keyiterator");
  1571. INIT_TYPE(&PySet_Type, "set");
  1572. INIT_TYPE(&PyUnicode_Type, "str");
  1573. INIT_TYPE(&PySlice_Type, "slice");
  1574. INIT_TYPE(&PyStaticMethod_Type, "static method");
  1575. INIT_TYPE(&PyComplex_Type, "complex");
  1576. INIT_TYPE(&PyFloat_Type, "float");
  1577. INIT_TYPE(&PyFrozenSet_Type, "frozenset");
  1578. INIT_TYPE(&PyProperty_Type, "property");
  1579. INIT_TYPE(&_PyManagedBuffer_Type, "managed buffer");
  1580. INIT_TYPE(&PyMemoryView_Type, "memoryview");
  1581. INIT_TYPE(&PyTuple_Type, "tuple");
  1582. INIT_TYPE(&PyEnum_Type, "enumerate");
  1583. INIT_TYPE(&PyReversed_Type, "reversed");
  1584. INIT_TYPE(&PyStdPrinter_Type, "StdPrinter");
  1585. INIT_TYPE(&PyCode_Type, "code");
  1586. INIT_TYPE(&PyFrame_Type, "frame");
  1587. INIT_TYPE(&PyCFunction_Type, "builtin function");
  1588. INIT_TYPE(&PyCMethod_Type, "builtin method");
  1589. INIT_TYPE(&PyMethod_Type, "method");
  1590. INIT_TYPE(&PyFunction_Type, "function");
  1591. INIT_TYPE(&PyDictProxy_Type, "dict proxy");
  1592. INIT_TYPE(&PyGen_Type, "generator");
  1593. INIT_TYPE(&PyGetSetDescr_Type, "get-set descriptor");
  1594. INIT_TYPE(&PyWrapperDescr_Type, "wrapper");
  1595. INIT_TYPE(&_PyMethodWrapper_Type, "method wrapper");
  1596. INIT_TYPE(&PyEllipsis_Type, "ellipsis");
  1597. INIT_TYPE(&PyMemberDescr_Type, "member descriptor");
  1598. INIT_TYPE(&_PyNamespace_Type, "namespace");
  1599. INIT_TYPE(&PyCapsule_Type, "capsule");
  1600. INIT_TYPE(&PyLongRangeIter_Type, "long range iterator");
  1601. INIT_TYPE(&PyCell_Type, "cell");
  1602. INIT_TYPE(&PyInstanceMethod_Type, "instance method");
  1603. INIT_TYPE(&PyClassMethodDescr_Type, "class method descr");
  1604. INIT_TYPE(&PyMethodDescr_Type, "method descr");
  1605. INIT_TYPE(&PyCallIter_Type, "call iter");
  1606. INIT_TYPE(&PySeqIter_Type, "sequence iterator");
  1607. INIT_TYPE(&PyPickleBuffer_Type, "pickle.PickleBuffer");
  1608. INIT_TYPE(&PyCoro_Type, "coroutine");
  1609. INIT_TYPE(&_PyCoroWrapper_Type, "coroutine wrapper");
  1610. INIT_TYPE(&_PyInterpreterID_Type, "interpreter ID");
  1611. return _PyStatus_OK();
  1612. #undef INIT_TYPE
  1613. }
  1614. void
  1615. _Py_NewReference(PyObject *op)
  1616. {
  1617. if (_Py_tracemalloc_config.tracing) {
  1618. _PyTraceMalloc_NewReference(op);
  1619. }
  1620. #ifdef Py_REF_DEBUG
  1621. _Py_RefTotal++;
  1622. #endif
  1623. Py_SET_REFCNT(op, 1);
  1624. #ifdef Py_TRACE_REFS
  1625. _Py_AddToAllObjects(op, 1);
  1626. #endif
  1627. }
  1628. #ifdef Py_TRACE_REFS
  1629. void
  1630. _Py_ForgetReference(PyObject *op)
  1631. {
  1632. if (Py_REFCNT(op) < 0) {
  1633. _PyObject_ASSERT_FAILED_MSG(op, "negative refcnt");
  1634. }
  1635. if (op == &refchain ||
  1636. op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
  1637. {
  1638. _PyObject_ASSERT_FAILED_MSG(op, "invalid object chain");
  1639. }
  1640. #ifdef SLOW_UNREF_CHECK
  1641. PyObject *p;
  1642. for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
  1643. if (p == op) {
  1644. break;
  1645. }
  1646. }
  1647. if (p == &refchain) {
  1648. /* Not found */
  1649. _PyObject_ASSERT_FAILED_MSG(op,
  1650. "object not found in the objects list");
  1651. }
  1652. #endif
  1653. op->_ob_next->_ob_prev = op->_ob_prev;
  1654. op->_ob_prev->_ob_next = op->_ob_next;
  1655. op->_ob_next = op->_ob_prev = NULL;
  1656. }
  1657. /* Print all live objects. Because PyObject_Print is called, the
  1658. * interpreter must be in a healthy state.
  1659. */
  1660. void
  1661. _Py_PrintReferences(FILE *fp)
  1662. {
  1663. PyObject *op;
  1664. fprintf(fp, "Remaining objects:\n");
  1665. for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
  1666. fprintf(fp, "%p [%zd] ", (void *)op, Py_REFCNT(op));
  1667. if (PyObject_Print(op, fp, 0) != 0) {
  1668. PyErr_Clear();
  1669. }
  1670. putc('\n', fp);
  1671. }
  1672. }
  1673. /* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
  1674. * doesn't make any calls to the Python C API, so is always safe to call.
  1675. */
  1676. void
  1677. _Py_PrintReferenceAddresses(FILE *fp)
  1678. {
  1679. PyObject *op;
  1680. fprintf(fp, "Remaining object addresses:\n");
  1681. for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
  1682. fprintf(fp, "%p [%zd] %s\n", (void *)op,
  1683. Py_REFCNT(op), Py_TYPE(op)->tp_name);
  1684. }
  1685. PyObject *
  1686. _Py_GetObjects(PyObject *self, PyObject *args)
  1687. {
  1688. int i, n;
  1689. PyObject *t = NULL;
  1690. PyObject *res, *op;
  1691. if (!PyArg_ParseTuple(args, "i|O", &n, &t))
  1692. return NULL;
  1693. op = refchain._ob_next;
  1694. res = PyList_New(0);
  1695. if (res == NULL)
  1696. return NULL;
  1697. for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
  1698. while (op == self || op == args || op == res || op == t ||
  1699. (t != NULL && !Py_IS_TYPE(op, (PyTypeObject *) t))) {
  1700. op = op->_ob_next;
  1701. if (op == &refchain)
  1702. return res;
  1703. }
  1704. if (PyList_Append(res, op) < 0) {
  1705. Py_DECREF(res);
  1706. return NULL;
  1707. }
  1708. op = op->_ob_next;
  1709. }
  1710. return res;
  1711. }
  1712. #endif
  1713. /* Hack to force loading of abstract.o */
  1714. Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
  1715. void
  1716. _PyObject_DebugTypeStats(FILE *out)
  1717. {
  1718. _PyDict_DebugMallocStats(out);
  1719. _PyFloat_DebugMallocStats(out);
  1720. _PyFrame_DebugMallocStats(out);
  1721. _PyList_DebugMallocStats(out);
  1722. _PyTuple_DebugMallocStats(out);
  1723. }
  1724. /* These methods are used to control infinite recursion in repr, str, print,
  1725. etc. Container objects that may recursively contain themselves,
  1726. e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
  1727. Py_ReprLeave() to avoid infinite recursion.
  1728. Py_ReprEnter() returns 0 the first time it is called for a particular
  1729. object and 1 every time thereafter. It returns -1 if an exception
  1730. occurred. Py_ReprLeave() has no return value.
  1731. See dictobject.c and listobject.c for examples of use.
  1732. */
  1733. int
  1734. Py_ReprEnter(PyObject *obj)
  1735. {
  1736. PyObject *dict;
  1737. PyObject *list;
  1738. Py_ssize_t i;
  1739. dict = PyThreadState_GetDict();
  1740. /* Ignore a missing thread-state, so that this function can be called
  1741. early on startup. */
  1742. if (dict == NULL)
  1743. return 0;
  1744. list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
  1745. if (list == NULL) {
  1746. if (PyErr_Occurred()) {
  1747. return -1;
  1748. }
  1749. list = PyList_New(0);
  1750. if (list == NULL)
  1751. return -1;
  1752. if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
  1753. return -1;
  1754. Py_DECREF(list);
  1755. }
  1756. i = PyList_GET_SIZE(list);
  1757. while (--i >= 0) {
  1758. if (PyList_GET_ITEM(list, i) == obj)
  1759. return 1;
  1760. }
  1761. if (PyList_Append(list, obj) < 0)
  1762. return -1;
  1763. return 0;
  1764. }
  1765. void
  1766. Py_ReprLeave(PyObject *obj)
  1767. {
  1768. PyObject *dict;
  1769. PyObject *list;
  1770. Py_ssize_t i;
  1771. PyObject *error_type, *error_value, *error_traceback;
  1772. PyErr_Fetch(&error_type, &error_value, &error_traceback);
  1773. dict = PyThreadState_GetDict();
  1774. if (dict == NULL)
  1775. goto finally;
  1776. list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
  1777. if (list == NULL || !PyList_Check(list))
  1778. goto finally;
  1779. i = PyList_GET_SIZE(list);
  1780. /* Count backwards because we always expect obj to be list[-1] */
  1781. while (--i >= 0) {
  1782. if (PyList_GET_ITEM(list, i) == obj) {
  1783. PyList_SetSlice(list, i, i + 1, NULL);
  1784. break;
  1785. }
  1786. }
  1787. finally:
  1788. /* ignore exceptions because there is no way to report them. */
  1789. PyErr_Restore(error_type, error_value, error_traceback);
  1790. }
  1791. /* Trashcan support. */
  1792. /* Add op to the _PyTrash_delete_later list. Called when the current
  1793. * call-stack depth gets large. op must be a currently untracked gc'ed
  1794. * object, with refcount 0. Py_DECREF must already have been called on it.
  1795. */
  1796. void
  1797. _PyTrash_deposit_object(PyObject *op)
  1798. {
  1799. PyInterpreterState *interp = _PyInterpreterState_GET();
  1800. struct _gc_runtime_state *gcstate = &interp->gc;
  1801. _PyObject_ASSERT(op, _PyObject_IS_GC(op));
  1802. _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
  1803. _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
  1804. _PyGCHead_SET_PREV(_Py_AS_GC(op), gcstate->trash_delete_later);
  1805. gcstate->trash_delete_later = op;
  1806. }
  1807. /* The equivalent API, using per-thread state recursion info */
  1808. void
  1809. _PyTrash_thread_deposit_object(PyObject *op)
  1810. {
  1811. PyThreadState *tstate = _PyThreadState_GET();
  1812. _PyObject_ASSERT(op, _PyObject_IS_GC(op));
  1813. _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
  1814. _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
  1815. _PyGCHead_SET_PREV(_Py_AS_GC(op), tstate->trash_delete_later);
  1816. tstate->trash_delete_later = op;
  1817. }
  1818. /* Deallocate all the objects in the _PyTrash_delete_later list. Called when
  1819. * the call-stack unwinds again.
  1820. */
  1821. void
  1822. _PyTrash_destroy_chain(void)
  1823. {
  1824. PyInterpreterState *interp = _PyInterpreterState_GET();
  1825. struct _gc_runtime_state *gcstate = &interp->gc;
  1826. while (gcstate->trash_delete_later) {
  1827. PyObject *op = gcstate->trash_delete_later;
  1828. destructor dealloc = Py_TYPE(op)->tp_dealloc;
  1829. gcstate->trash_delete_later =
  1830. (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
  1831. /* Call the deallocator directly. This used to try to
  1832. * fool Py_DECREF into calling it indirectly, but
  1833. * Py_DECREF was already called on this object, and in
  1834. * assorted non-release builds calling Py_DECREF again ends
  1835. * up distorting allocation statistics.
  1836. */
  1837. _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
  1838. ++gcstate->trash_delete_nesting;
  1839. (*dealloc)(op);
  1840. --gcstate->trash_delete_nesting;
  1841. }
  1842. }
  1843. /* The equivalent API, using per-thread state recursion info */
  1844. void
  1845. _PyTrash_thread_destroy_chain(void)
  1846. {
  1847. PyThreadState *tstate = _PyThreadState_GET();
  1848. /* We need to increase trash_delete_nesting here, otherwise,
  1849. _PyTrash_thread_destroy_chain will be called recursively
  1850. and then possibly crash. An example that may crash without
  1851. increase:
  1852. N = 500000 # need to be large enough
  1853. ob = object()
  1854. tups = [(ob,) for i in range(N)]
  1855. for i in range(49):
  1856. tups = [(tup,) for tup in tups]
  1857. del tups
  1858. */
  1859. assert(tstate->trash_delete_nesting == 0);
  1860. ++tstate->trash_delete_nesting;
  1861. while (tstate->trash_delete_later) {
  1862. PyObject *op = tstate->trash_delete_later;
  1863. destructor dealloc = Py_TYPE(op)->tp_dealloc;
  1864. tstate->trash_delete_later =
  1865. (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
  1866. /* Call the deallocator directly. This used to try to
  1867. * fool Py_DECREF into calling it indirectly, but
  1868. * Py_DECREF was already called on this object, and in
  1869. * assorted non-release builds calling Py_DECREF again ends
  1870. * up distorting allocation statistics.
  1871. */
  1872. _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
  1873. (*dealloc)(op);
  1874. assert(tstate->trash_delete_nesting == 1);
  1875. }
  1876. --tstate->trash_delete_nesting;
  1877. }
  1878. int
  1879. _PyTrash_begin(PyThreadState *tstate, PyObject *op)
  1880. {
  1881. if (tstate->trash_delete_nesting >= PyTrash_UNWIND_LEVEL) {
  1882. /* Store the object (to be deallocated later) and jump past
  1883. * Py_TRASHCAN_END, skipping the body of the deallocator */
  1884. _PyTrash_thread_deposit_object(op);
  1885. return 1;
  1886. }
  1887. ++tstate->trash_delete_nesting;
  1888. return 0;
  1889. }
  1890. void
  1891. _PyTrash_end(PyThreadState *tstate)
  1892. {
  1893. --tstate->trash_delete_nesting;
  1894. if (tstate->trash_delete_later && tstate->trash_delete_nesting <= 0) {
  1895. _PyTrash_thread_destroy_chain();
  1896. }
  1897. }
  1898. /* bpo-40170: It's only be used in Py_TRASHCAN_BEGIN macro to hide
  1899. implementation details. */
  1900. int
  1901. _PyTrash_cond(PyObject *op, destructor dealloc)
  1902. {
  1903. return Py_TYPE(op)->tp_dealloc == dealloc;
  1904. }
  1905. void _Py_NO_RETURN
  1906. _PyObject_AssertFailed(PyObject *obj, const char *expr, const char *msg,
  1907. const char *file, int line, const char *function)
  1908. {
  1909. fprintf(stderr, "%s:%d: ", file, line);
  1910. if (function) {
  1911. fprintf(stderr, "%s: ", function);
  1912. }
  1913. fflush(stderr);
  1914. if (expr) {
  1915. fprintf(stderr, "Assertion \"%s\" failed", expr);
  1916. }
  1917. else {
  1918. fprintf(stderr, "Assertion failed");
  1919. }
  1920. fflush(stderr);
  1921. if (msg) {
  1922. fprintf(stderr, ": %s", msg);
  1923. }
  1924. fprintf(stderr, "\n");
  1925. fflush(stderr);
  1926. if (_PyObject_IsFreed(obj)) {
  1927. /* It seems like the object memory has been freed:
  1928. don't access it to prevent a segmentation fault. */
  1929. fprintf(stderr, "<object at %p is freed>\n", obj);
  1930. fflush(stderr);
  1931. }
  1932. else {
  1933. /* Display the traceback where the object has been allocated.
  1934. Do it before dumping repr(obj), since repr() is more likely
  1935. to crash than dumping the traceback. */
  1936. void *ptr;
  1937. PyTypeObject *type = Py_TYPE(obj);
  1938. if (_PyType_IS_GC(type)) {
  1939. ptr = (void *)((char *)obj - sizeof(PyGC_Head));
  1940. }
  1941. else {
  1942. ptr = (void *)obj;
  1943. }
  1944. _PyMem_DumpTraceback(fileno(stderr), ptr);
  1945. /* This might succeed or fail, but we're about to abort, so at least
  1946. try to provide any extra info we can: */
  1947. _PyObject_Dump(obj);
  1948. fprintf(stderr, "\n");
  1949. fflush(stderr);
  1950. }
  1951. Py_FatalError("_PyObject_AssertFailed");
  1952. }
  1953. void
  1954. _Py_Dealloc(PyObject *op)
  1955. {
  1956. destructor dealloc = Py_TYPE(op)->tp_dealloc;
  1957. #ifdef Py_TRACE_REFS
  1958. _Py_ForgetReference(op);
  1959. #endif
  1960. (*dealloc)(op);
  1961. }
  1962. PyObject **
  1963. PyObject_GET_WEAKREFS_LISTPTR(PyObject *op)
  1964. {
  1965. return _PyObject_GET_WEAKREFS_LISTPTR(op);
  1966. }
  1967. #undef Py_NewRef
  1968. #undef Py_XNewRef
  1969. // Export Py_NewRef() and Py_XNewRef() as regular functions for the stable ABI.
  1970. PyObject*
  1971. Py_NewRef(PyObject *obj)
  1972. {
  1973. return _Py_NewRef(obj);
  1974. }
  1975. PyObject*
  1976. Py_XNewRef(PyObject *obj)
  1977. {
  1978. return _Py_XNewRef(obj);
  1979. }
  1980. #ifdef __cplusplus
  1981. }
  1982. #endif