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.

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