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