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.

2222 lines
61 KiB

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