1 
2 /* Method object implementation */
3 
4 #include "Python.h"
5 #include "internal/mem.h"
6 #include "internal/pystate.h"
7 #include "structmember.h"
8 
9 /* Free list for method objects to safe malloc/free overhead
10  * The m_self element is used to chain the objects.
11  */
12 static PyCFunctionObject *free_list = NULL;
13 static int numfree = 0;
14 #ifndef PyCFunction_MAXFREELIST
15 #define PyCFunction_MAXFREELIST 256
16 #endif
17 
18 /* undefine macro trampoline to PyCFunction_NewEx */
19 #undef PyCFunction_New
20 
21 PyAPI_FUNC(PyObject *)
PyCFunction_New(PyMethodDef * ml,PyObject * self)22 PyCFunction_New(PyMethodDef *ml, PyObject *self)
23 {
24     return PyCFunction_NewEx(ml, self, NULL);
25 }
26 
27 PyObject *
PyCFunction_NewEx(PyMethodDef * ml,PyObject * self,PyObject * module)28 PyCFunction_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module)
29 {
30     PyCFunctionObject *op;
31     op = free_list;
32     if (op != NULL) {
33         free_list = (PyCFunctionObject *)(op->m_self);
34         (void)PyObject_INIT(op, &PyCFunction_Type);
35         numfree--;
36     }
37     else {
38         op = PyObject_GC_New(PyCFunctionObject, &PyCFunction_Type);
39         if (op == NULL)
40             return NULL;
41     }
42     op->m_weakreflist = NULL;
43     op->m_ml = ml;
44     Py_XINCREF(self);
45     op->m_self = self;
46     Py_XINCREF(module);
47     op->m_module = module;
48     _PyObject_GC_TRACK(op);
49     return (PyObject *)op;
50 }
51 
52 PyCFunction
PyCFunction_GetFunction(PyObject * op)53 PyCFunction_GetFunction(PyObject *op)
54 {
55     if (!PyCFunction_Check(op)) {
56         PyErr_BadInternalCall();
57         return NULL;
58     }
59     return PyCFunction_GET_FUNCTION(op);
60 }
61 
62 PyObject *
PyCFunction_GetSelf(PyObject * op)63 PyCFunction_GetSelf(PyObject *op)
64 {
65     if (!PyCFunction_Check(op)) {
66         PyErr_BadInternalCall();
67         return NULL;
68     }
69     return PyCFunction_GET_SELF(op);
70 }
71 
72 int
PyCFunction_GetFlags(PyObject * op)73 PyCFunction_GetFlags(PyObject *op)
74 {
75     if (!PyCFunction_Check(op)) {
76         PyErr_BadInternalCall();
77         return -1;
78     }
79     return PyCFunction_GET_FLAGS(op);
80 }
81 
82 /* Methods (the standard built-in methods, that is) */
83 
84 static void
meth_dealloc(PyCFunctionObject * m)85 meth_dealloc(PyCFunctionObject *m)
86 {
87     _PyObject_GC_UNTRACK(m);
88     if (m->m_weakreflist != NULL) {
89         PyObject_ClearWeakRefs((PyObject*) m);
90     }
91     Py_XDECREF(m->m_self);
92     Py_XDECREF(m->m_module);
93     if (numfree < PyCFunction_MAXFREELIST) {
94         m->m_self = (PyObject *)free_list;
95         free_list = m;
96         numfree++;
97     }
98     else {
99         PyObject_GC_Del(m);
100     }
101 }
102 
103 static PyObject *
meth_reduce(PyCFunctionObject * m)104 meth_reduce(PyCFunctionObject *m)
105 {
106     _Py_IDENTIFIER(getattr);
107 
108     if (m->m_self == NULL || PyModule_Check(m->m_self))
109         return PyUnicode_FromString(m->m_ml->ml_name);
110 
111     return Py_BuildValue("N(Os)", _PyEval_GetBuiltinId(&PyId_getattr),
112                          m->m_self, m->m_ml->ml_name);
113 }
114 
115 static PyMethodDef meth_methods[] = {
116     {"__reduce__", (PyCFunction)meth_reduce, METH_NOARGS, NULL},
117     {NULL, NULL}
118 };
119 
120 static PyObject *
meth_get__text_signature__(PyCFunctionObject * m,void * closure)121 meth_get__text_signature__(PyCFunctionObject *m, void *closure)
122 {
123     return _PyType_GetTextSignatureFromInternalDoc(m->m_ml->ml_name, m->m_ml->ml_doc);
124 }
125 
126 static PyObject *
meth_get__doc__(PyCFunctionObject * m,void * closure)127 meth_get__doc__(PyCFunctionObject *m, void *closure)
128 {
129     return _PyType_GetDocFromInternalDoc(m->m_ml->ml_name, m->m_ml->ml_doc);
130 }
131 
132 static PyObject *
meth_get__name__(PyCFunctionObject * m,void * closure)133 meth_get__name__(PyCFunctionObject *m, void *closure)
134 {
135     return PyUnicode_FromString(m->m_ml->ml_name);
136 }
137 
138 static PyObject *
meth_get__qualname__(PyCFunctionObject * m,void * closure)139 meth_get__qualname__(PyCFunctionObject *m, void *closure)
140 {
141     /* If __self__ is a module or NULL, return m.__name__
142        (e.g. len.__qualname__ == 'len')
143 
144        If __self__ is a type, return m.__self__.__qualname__ + '.' + m.__name__
145        (e.g. dict.fromkeys.__qualname__ == 'dict.fromkeys')
146 
147        Otherwise return type(m.__self__).__qualname__ + '.' + m.__name__
148        (e.g. [].append.__qualname__ == 'list.append') */
149     PyObject *type, *type_qualname, *res;
150     _Py_IDENTIFIER(__qualname__);
151 
152     if (m->m_self == NULL || PyModule_Check(m->m_self))
153         return PyUnicode_FromString(m->m_ml->ml_name);
154 
155     type = PyType_Check(m->m_self) ? m->m_self : (PyObject*)Py_TYPE(m->m_self);
156 
157     type_qualname = _PyObject_GetAttrId(type, &PyId___qualname__);
158     if (type_qualname == NULL)
159         return NULL;
160 
161     if (!PyUnicode_Check(type_qualname)) {
162         PyErr_SetString(PyExc_TypeError, "<method>.__class__."
163                         "__qualname__ is not a unicode object");
164         Py_XDECREF(type_qualname);
165         return NULL;
166     }
167 
168     res = PyUnicode_FromFormat("%S.%s", type_qualname, m->m_ml->ml_name);
169     Py_DECREF(type_qualname);
170     return res;
171 }
172 
173 static int
meth_traverse(PyCFunctionObject * m,visitproc visit,void * arg)174 meth_traverse(PyCFunctionObject *m, visitproc visit, void *arg)
175 {
176     Py_VISIT(m->m_self);
177     Py_VISIT(m->m_module);
178     return 0;
179 }
180 
181 static PyObject *
meth_get__self__(PyCFunctionObject * m,void * closure)182 meth_get__self__(PyCFunctionObject *m, void *closure)
183 {
184     PyObject *self;
185 
186     self = PyCFunction_GET_SELF(m);
187     if (self == NULL)
188         self = Py_None;
189     Py_INCREF(self);
190     return self;
191 }
192 
193 static PyGetSetDef meth_getsets [] = {
194     {"__doc__",  (getter)meth_get__doc__,  NULL, NULL},
195     {"__name__", (getter)meth_get__name__, NULL, NULL},
196     {"__qualname__", (getter)meth_get__qualname__, NULL, NULL},
197     {"__self__", (getter)meth_get__self__, NULL, NULL},
198     {"__text_signature__", (getter)meth_get__text_signature__, NULL, NULL},
199     {0}
200 };
201 
202 #define OFF(x) offsetof(PyCFunctionObject, x)
203 
204 static PyMemberDef meth_members[] = {
205     {"__module__",    T_OBJECT,     OFF(m_module), PY_WRITE_RESTRICTED},
206     {NULL}
207 };
208 
209 static PyObject *
meth_repr(PyCFunctionObject * m)210 meth_repr(PyCFunctionObject *m)
211 {
212     if (m->m_self == NULL || PyModule_Check(m->m_self))
213         return PyUnicode_FromFormat("<built-in function %s>",
214                                    m->m_ml->ml_name);
215     return PyUnicode_FromFormat("<built-in method %s of %s object at %p>",
216                                m->m_ml->ml_name,
217                                m->m_self->ob_type->tp_name,
218                                m->m_self);
219 }
220 
221 static PyObject *
meth_richcompare(PyObject * self,PyObject * other,int op)222 meth_richcompare(PyObject *self, PyObject *other, int op)
223 {
224     PyCFunctionObject *a, *b;
225     PyObject *res;
226     int eq;
227 
228     if ((op != Py_EQ && op != Py_NE) ||
229         !PyCFunction_Check(self) ||
230         !PyCFunction_Check(other))
231     {
232         Py_RETURN_NOTIMPLEMENTED;
233     }
234     a = (PyCFunctionObject *)self;
235     b = (PyCFunctionObject *)other;
236     eq = a->m_self == b->m_self;
237     if (eq)
238         eq = a->m_ml->ml_meth == b->m_ml->ml_meth;
239     if (op == Py_EQ)
240         res = eq ? Py_True : Py_False;
241     else
242         res = eq ? Py_False : Py_True;
243     Py_INCREF(res);
244     return res;
245 }
246 
247 static Py_hash_t
meth_hash(PyCFunctionObject * a)248 meth_hash(PyCFunctionObject *a)
249 {
250     Py_hash_t x, y;
251     if (a->m_self == NULL)
252         x = 0;
253     else {
254         x = PyObject_Hash(a->m_self);
255         if (x == -1)
256             return -1;
257     }
258     y = _Py_HashPointer((void*)(a->m_ml->ml_meth));
259     if (y == -1)
260         return -1;
261     x ^= y;
262     if (x == -1)
263         x = -2;
264     return x;
265 }
266 
267 
268 PyTypeObject PyCFunction_Type = {
269     PyVarObject_HEAD_INIT(&PyType_Type, 0)
270     "builtin_function_or_method",
271     sizeof(PyCFunctionObject),
272     0,
273     (destructor)meth_dealloc,                   /* tp_dealloc */
274     0,                                          /* tp_print */
275     0,                                          /* tp_getattr */
276     0,                                          /* tp_setattr */
277     0,                                          /* tp_reserved */
278     (reprfunc)meth_repr,                        /* tp_repr */
279     0,                                          /* tp_as_number */
280     0,                                          /* tp_as_sequence */
281     0,                                          /* tp_as_mapping */
282     (hashfunc)meth_hash,                        /* tp_hash */
283     PyCFunction_Call,                           /* tp_call */
284     0,                                          /* tp_str */
285     PyObject_GenericGetAttr,                    /* tp_getattro */
286     0,                                          /* tp_setattro */
287     0,                                          /* tp_as_buffer */
288     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
289     0,                                          /* tp_doc */
290     (traverseproc)meth_traverse,                /* tp_traverse */
291     0,                                          /* tp_clear */
292     meth_richcompare,                           /* tp_richcompare */
293     offsetof(PyCFunctionObject, m_weakreflist), /* tp_weaklistoffset */
294     0,                                          /* tp_iter */
295     0,                                          /* tp_iternext */
296     meth_methods,                               /* tp_methods */
297     meth_members,                               /* tp_members */
298     meth_getsets,                               /* tp_getset */
299     0,                                          /* tp_base */
300     0,                                          /* tp_dict */
301 };
302 
303 /* Clear out the free list */
304 
305 int
PyCFunction_ClearFreeList(void)306 PyCFunction_ClearFreeList(void)
307 {
308     int freelist_size = numfree;
309 
310     while (free_list) {
311         PyCFunctionObject *v = free_list;
312         free_list = (PyCFunctionObject *)(v->m_self);
313         PyObject_GC_Del(v);
314         numfree--;
315     }
316     assert(numfree == 0);
317     return freelist_size;
318 }
319 
320 void
PyCFunction_Fini(void)321 PyCFunction_Fini(void)
322 {
323     (void)PyCFunction_ClearFreeList();
324 }
325 
326 /* Print summary info about the state of the optimized allocator */
327 void
_PyCFunction_DebugMallocStats(FILE * out)328 _PyCFunction_DebugMallocStats(FILE *out)
329 {
330     _PyDebugAllocatorStats(out,
331                            "free PyCFunctionObject",
332                            numfree, sizeof(PyCFunctionObject));
333 }
334