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.

2217 lines
62 KiB

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