object.c 73 KB

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