object.c 72 KB

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